我如何正确使用 componentWillReceiveProps()?

IT技术 javascript reactjs
2021-05-21 01:15:34

我正在尝试在收到新props后立即更新子组件。但是,componentWillReceiveProps()在props实际更新之前调用了我的子组件。阅读这篇文章后,我确实明白了原因,但它并没有解释我如何解决我的问题。

props更新componentWillReceiveProps() 如何调用

现在我通过让超时运行等待实际更新来欺骗我的方式,但我真的不喜欢这个解决方案。

  componentWillReceiveProps(){
   var timeOut = setTimeout(() => this.loadPosts(), 100)
  },

谢谢id提前!

2个回答

props更新componentWillReceiveProps 需要调用吗?或者你可以使用这个nextProps论点吗?

例如。如果你重写为:

componentWillReceiveProps(nextProps){
  this.loadPosts(nextProps)
},

然后当然还要重写 的签名loadPosts以允许手动传入props:

loadPosts(props = this.props){
  // do something with props
  ...
}

使用componentDidUpdate(prevProps, prevState)当它被调用时,会传递两个参数:prevPropsprevState这是 的倒数componentWillUpdate传递的值是值是什么,this.props并且this.state是当前值。