admin管理员组文章数量:1422029
If I have a react ponent, 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
?. Or is it bad to do that, and if so, why?
If I have a react ponent, 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
?. Or is it bad to do that, and if so, why?
- Yeah it's bad practise, there is a reason why lifecyle events and setState / props are there. If you need to use forceUpdate then it indicates that you are doing something wrong, imho – Icepickle Commented Mar 3, 2018 at 19:15
- This might throw more light on it stackoverflow./questions/47237556/… – Shubham Khatri Commented Mar 3, 2018 at 19:28
1 Answer
Reset to default 4forceUpdate()
is actually useful in scenarios like the one you're describing.
From the docs:
By default, when your ponent’s state or props change, your ponent will re-render. If your
render()
method depends on some other data, you can tell React that the ponent needs re-rendering by callingforceUpdate()
.
The caveat, however, is that it will skip shouldComponentUpdate()
, so you're not getting the optimization benefit.
Also, using forceUpdate()
"bypasses" the proper lifecycle, making your code less straight-forward and possibly harder to understand and maintain.
It is therefore remended to use state
and props
when possible.
Normally you should try to avoid all uses of forceUpdate() and only read from
this.props
andthis.state
in render().
本文标签: javascriptUsing forceUpdate instead of setState in ReactStack Overflow
版权声明:本文标题:javascript - Using forceUpdate instead of setState in React? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745357321a2655131.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论