componentWillRecieveProps 方法无法正常工作:ReactJS

IT技术 javascript reactjs
2021-04-07 09:59:15

以下子组件从其父组件接收props。然后它使用getInitialState.props将 props 设置为它自己的状态,并使用this.state.

componentWillRecieveProps当子组件收到新props时,我使用它来更新子组件的状态。

最初,当组件被调用时,它可以正常工作。第二次传props的时候会出现这个问题,触发传props的对应按钮需要点击两次才能设置child的状态。

我可能使用componentWillRecieveProps不当?

getInitialState: function() {
  return {
    pitch: this.props.booking.pitch,
    email: this.props.booking.email,
    firstName: this.props.booking.firstName,
    arrivalDate: this.props.booking.arrivalDate,
  }
}, 

componentWillReceiveProps: function (props) {
  this.setState({
    pitch: this.props.booking.pitch,
    email: this.props.booking.email,
    firstName: this.props.booking.firstName,
    arrivalDate: this.props.booking.arrivalDate,
  })
},

完整代码:

1个回答

我可能会错误地使用 componentWillRecieveProps?

是的,因为你需要使用props.keyname(props 传递给这个方法的参数),而不是this.propsin componentWillReceiveProps

原因是,在此lifecycle方法内部this.props将具有以前的props值而不是新值,在此lifecycle方法之后this.props将具有新props值。

根据DOC

componentWillReceiveProps() 在挂载的组件接收新的 props 之前被调用。如果您需要更新状态以响应 prop 更改(例如,重置它),您可以比较 this.props 和 nextProps 并在此方法中使用 this.setState() 执行状态转换。

这是因为componentWillReceiveProps每个setState内部父newprops组件都会被调用,所以在设置内部子组件之前,我们应该先比较 prev 值和新值,可能是父内部的一些其他state值已更改,而不是我们传递给子组件的值。

console.logthis.propsnewProps和检查结果。

用这个:

componentWillReceiveProps: function (newProps) {
    this.setState({
        pitch: newProps.booking.pitch,
        email: newProps.booking.email,
        firstName: newProps.booking.firstName,
        arrivalDate: newProps.booking.arrivalDate,
    })
    console.log('previous value', this.props);    //print the previous values
    console.log('new values', newProps);          //new values
},
很高兴,它帮助了你 :) 一旦我浪费了足够的时间。
2021-05-25 09:59:15
现在您已经在答案中引用了它,这似乎很明显。接受为正确答案。
2021-05-31 09:59:15
太棒了,谢谢@Mayank,无法从文档中解决这个问题。
2021-06-05 09:59:15