gpt4 book ai didi

reactjs - 在React中,setState和forceUpdate有什么区别

转载 作者:行者123 更新时间:2023-12-03 13:18:18 24 4
gpt4 key购买 nike

重写shouldComponentUpdate的组件中,forceUpdate和setState之间有什么区别吗?

更新:我已经知道文档所说的内容,并且不建议使用强制更新方法。我只是想更深入地了解正在发生的事情。我想知道为什么?我已经知道 setState 将传递的对象(状态“delta” - 有点像 SQL 更新)与当前状态对象合并。

假设一个简单的用例:不需要撤消或时间旅行功能。不需要在shouldComponentUpdate内部进行指针比较。事实上,根本不需要使用shouldComponentUpdate。

在这种情况下,在我看来,改变状态和调用forceUpdate()是使用React的完全有效的方法。从黑盒的角度来看,这两种技术似乎具有完全相同的效果:

技术#1:this.state.x = 10;this.forceUpdate();

技术#2:this.state.setState({x:10});

再说一次,我已经知道有些人宁愿永远不改变状态。并使用函数式编程风格。我只是想知道是否有任何技术原因可以避免技术#1。或者我错过了什么?

最佳答案

关于setState()的一般信息

setState() 函数通常用于使用一个或多个状态属性来更新组件状态。这是改变状态和管理 View 更新的典型方法。

来自官方文档:

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

<小时/>

关于forceUpdate()的一般信息

forceUpdate() 函数只是强制重新渲染相关组件及其子组件的一种方法。它根本不会改变状态。

您应该尽可能避免使用此函数,因为它偏离了 React 思维方式,在 React 思维方式中,您的状态和 props 唯一负责使您的应用程序逻辑与您的 View 保持最新。

来自官方文档:

By default, when your component's state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().

<小时/>

差异

需要注意的是,forceUpdate()跳过检查 shouldComponentUpdate() 中的逻辑(如果有的话),其中setState() 不跳过它。

这里有趣的一点是,以下两行将始终产生相同的结果:

this.setState(this.state);
this.forceUpdate();

...除非 shouldComponentUpdate() 可以返回 false,如上所述。

除上述内容外,两者在功能上没有区别。

关于reactjs - 在React中,setState和forceUpdate有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43841930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com