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().
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745357321a4624196.html
评论列表(0条)