【问题标题】:React replace componentWillReceivePropsReact 替换组件WillReceiveProps
【发布时间】:2020-07-10 03:51:18
【问题描述】:

在我的子组件中有以下方法可以更新 prop 更改的状态,效果很好

  componentWillReceiveProps(nextProps) {
    // update original states
    this.setState({
      fields: nextProps.fields,
      containerClass: nextProps.containerClass
    });
  }

我收到Warning: Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code.

我尝试更新,但到目前为止没有任何成功

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.fields !== prevState.fields) {
      return { fields: nextProps.fields };
    }
  }

  componentDidUpdate(nextProps) {
    console.log(nextProps);
    this.setState({
      fields: nextProps.fields,
      containerClass: nextProps.containerClass
    });
  }

因为我进入了无限循环。

如何根据新道具正确更新我的状态

【问题讨论】:

    标签: reactjs updates deprecated prop


    【解决方案1】:

    你会得到循环,因为每次组件更新时你都会设置新的状态。因此,如果状态更新,则意味着组件更新,并且您再次更新它。 因此,您需要防止在状态更改时更新组件。

    componentDidUpdate(prevProps, nextProps) {
      if(prevProps !== this.props){
       console.log(nextProps);
       this.setState({
         fields: nextProps.fields,
         containerClass: nextProps.containerClass
       });
     }
    }
    

    【讨论】:

    • React doc,第二个参数是prevState。所以,componentDidUpdate(prevProps, prevState, snapshot)。我想你可能会检查你的逻辑
    【解决方案2】:

    您设置了状态,这将触发另一个调用并更新将再次调用,依此类推。 您必须先检查值是否在变化,然后再设置状态。

    componentDidUpdate(nextProps) {
        console.log(nextProps);
        if (nextProps.fields !== this.state.nextProps.fields){
            this.setState({
               fields: nextProps.fields,
               containerClass: nextProps.containerClass
            });
        }
      }
    

    我推荐你使用钩子see here

    【讨论】:

      【解决方案3】:

      我之前去过那里很多次.. 您需要做的就是将this.setState({.. 包装在一些代码中。

      您有componentDidUpdate(prevProps, prevState, snapshot),所以只需比较nextProps.fields 和/或nextProps.containerClass 是否不同于this.props.fieldsthis.props.containerClass - 然后才设置状态

      顺便说一句,在 CDM 中 nextProps 实际上是 prevProps

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-16
        • 2020-12-29
        • 2018-06-05
        • 1970-01-01
        • 2017-09-05
        • 2017-03-09
        相关资源
        最近更新 更多