反应替换 componentWillReceiveProps

React replace componentWillReceiveProps

我的子组件中有以下方法可以在 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
    });
  }

因为我进入了无限循环。

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

我以前去过那里很多次..你需要做的就是用一些条件包装this.setState({..

你有 componentDidUpdate(prevProps, prevState, snapshot) 所以只要比较 nextProps.fields and/or nextProps.containerClass 是否不同于 this.props.fieldsthis.props.containerClass - 然后才设置州

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

您设置状态,这将触发另一个调用和更新,这将再次调用等等。 您必须先检查值是否发生变化,然后再设置状态。

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

我推荐你使用 hooks see here

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

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