OM The Eternity OM The Eternity - 1 year ago 58
React JSX Question

Calling setState in constructor gives warning

I have a code written by someone else where the

constructor
where I have
state
initialized but also called the
setState
if
props
is
undefined
, the code is as below:

constructor(props) {
super(props);
this.state = {
subId: props.match.params.subId
}
if(props!==undefined){
this.setState({
subId: props.match.params.subId
});
}
}


When I execute my module I get the warning in console as warning.js:35 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.

I googled about it and found that the setState should not be called in constructor. But still cannot understand the thing done here in constructor and the ideal way expected by react. Need some help in understanding, whether the code done in constructor is correct, if yes, why, if no, why?

Answer Source

Besides setting the state with setState it also has the mechanism of re-rendering on change. The constructor is executed before it is actually mounted and will not render something. That's why it makes no sense to use setState in the constructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download