我如何正确使用componentWillReceiveProps()?

Jon*_*ner 3 javascript reactjs

我正在尝试在收到新道具后立即更新子组件.但是,componentWillReceiveProps()在我的子组件中,在道具实际更新之前调用.阅读本文后,我明白为什么,但它没有解释我如何解决我的问题.

道具更新componentWillReceiveProps() 如何打电话?

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

  componentWillReceiveProps(){
   var timeOut = setTimeout(() => this.loadPosts(), 100)
  },
Run Code Online (Sandbox Code Playgroud)

谢谢你提前!

小智 7

道具更新componentWillReceiveProps 是否有必要打电话?或者你能用这个nextProps论点吗?

例如.如果你改写为:

componentWillReceiveProps(nextProps){
  this.loadPosts(nextProps)
},
Run Code Online (Sandbox Code Playgroud)

然后当然也重写签名loadPosts允许手动传递道具:

loadPosts(props = this.props){
  // do something with props
  ...
}
Run Code Online (Sandbox Code Playgroud)