繁体   English   中英

使用prop更新组件的状态

[英]Updating component's state using props

我试图以这种方式使用收到的道具来更新某些组件的状态:

componentWillReceiveProps(nextProps) {
   if(nextProps.history.length <= 2) {
      this.setState({
         history: nextProps.history
      });
   }
}

问题在于,当父级传递的历史记录长度大于2时,状态仍在变异。 有任何想法吗?

谢谢

生命周期方法componentWillReceiveProps已弃用。 您应该使用getDerivedStateFromProps

在初始安装和后续更新上,都在调用render方法之前立即调用getDerivedStateFromProps。 它应该返回一个对象以更新状态,或者返回null则不更新任何内容。

您可以使用componentDidUpdate()生命周期方法或静态的getDerivedStateFromProps()方法。

static getDerivedStateFromProps(props, state) {
    return ({
        history: props.history.length <= 2 ? props.history : state.history
    })
}

或者,如果您喜欢:

componentDidUpdate(prevProps) {
    const { history } = this.props;
    if((prevProps.history !== history) && history.length <= 2) {
        this.setState({ history })
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM