why this.setState does not work.
constructor(props) {
super(props);
this.state ={
obj: [],
}
}
,
componentDidUpdate(prevProps){
const { obj } = this.props;
this.setState({obj});
}
}
If you look at your dev console you'll see an error when that console log is supposed to occur, because you're using a "normal" function without any kind of this
preservation. Instead, once that function gets called the this
identifier will be referencing the global context (eg window
), rather than your component.
Use an arrow function to make sure this
is the one you actually meant, and you'll see that setState
worked just fine:
componentDidUpdate(prevProps){
this.setState({
siteDataState: this.props.siteData
}, () => {
console.log(this.state.siteDataState);
});
}
That said, this is going to cascade-trigger because you're changing the component in the function that triggers when the component changes , so put some if
code in there that makes sure that this.state.siteDataState
isn't already what's in this.props.siteData
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.