无法在React中的componentWillReceiveProps中设置状态

Ada*_*ite 2 reactjs

我试图用父组件收到的新道具更新组件的状态.

但是,setState调用似乎没有像我期望的那样工作.

我理解componentWillReceiveProps不会重新渲染组件,但它似乎甚至不允许setState调用.

我有什么想法可能做错了吗?

代码:

componentWillReceiveProps (nextProps) {
  this.setState({name: nextProps.site.name});
  console.log(nextProps.site.name); // logs the updated name
  console.log(this.state.name); // logs the old name, even after presumably being set again
}
Run Code Online (Sandbox Code Playgroud)

小智 5

这是异步完成的.因此,您可能无法在方法中看到更新.检查componentDidUpdate中的内容.


小智 5

您可以在setState回调中看到结果,如下所示:

this.setState({name: nextProps.site.name} , ()=>{

console.log(this.state.name);

});
Run Code Online (Sandbox Code Playgroud)