I have a code written by someone else where the constructor
where I havestate
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?