[英]Using forceUpdate instead of setState in React?
If I have a react component, and I just set its class variables, ie如果我有一个反应组件,我只是设置它的类变量,即
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.numberElements = 20;
this.color = 'red';
}
render() {
...
}
}
Can't I just call this.forceUpdate()
to issue a re-render (whenever I update my class variables) instead of maintaining a state and calling setState
?.我不能只调用this.forceUpdate()
来发出重新渲染(每当我更新我的类变量时)而不是维护状态并调用setState
吗? Or is it bad to do that, and if so, why?或者这样做不好,如果是这样,为什么?
forceUpdate()
is actually useful in scenarios like the one you're describing. forceUpdate()
实际上在您所描述的场景中很有用。
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 callingforceUpdate()
.如果您的render()
方法依赖于其他一些数据,您可以通过调用forceUpdate()
告诉 React 该组件需要重新渲染。
The caveat, however, is that it will skip shouldComponentUpdate()
, so you're not getting the optimization benefit.但需要注意的是,它会跳过shouldComponentUpdate()
,因此您无法获得优化优势。
Also, using forceUpdate()
"bypasses" the proper lifecycle, making your code less straight-forward and possibly harder to understand and maintain.此外,使用forceUpdate()
“绕过”正确的生命周期,使您的代码不那么直接,并且可能更难理解和维护。
It is therefore recommended to use state
and props
when possible.因此建议尽可能使用state
和props
。
Normally you should try to avoid all uses of forceUpdate() and only read from
this.props
andthis.state
in render().通常你应该尽量避免使用 forceUpdate() 并且只在 render() 中读取this.props
和this.state
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.