微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

reactjs – 在React中,setState和forceUpdate之间有什么区别

在不覆盖shouldComponentUpdate的组件中,forceUpdate和setState之间有什么区别吗?

更新:我已经知道文档说的内容,并且forceUpdate不是推荐的方法.我只是想更深入地了解正在发生的事情.我想知道为什么?我已经知道setState将传递的对象(状态“delta” – 类似于sql update)与当前状态对象合并.

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

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

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

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

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

关于setState()的一般信息

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

来自官方文档:

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思维模式,您的状态和道具全权负责使您的应用程序逻辑与您的视图保持同步.

来自官方文档:

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,如上所述.

除此之外,两者之间没有功能差异.

原文地址:https://www.jb51.cc/react/301110.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐