我如何正确使用componentWillReceiveProps()?

时间:2017-01-04 00:14:14

标签: javascript reactjs

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

道具更新之后如何致电componentWillReceiveProps()

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

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

感谢id advance!

2 个答案:

答案 0 :(得分:7)

道具更新之后是否有必要致电componentWillReceiveProps ?或者您可以使用nextProps argument吗?

EG。如果你重写为:

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

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

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

答案 1 :(得分:4)

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