React 替换 componentWillReceiveProps。

6
在我的子组件中有以下方法,可以在属性更改时更新状态,这很好用。
  componentWillReceiveProps(nextProps) {
    // update original states
    this.setState({
      fields: nextProps.fields,
      containerClass: nextProps.containerClass
    });
  }

我收到了警告:Warning: 在严格模式下使用 UNSAFE_componentWillReceiveProps 并不被推荐,因为这可能表明您的代码存在漏洞。

我试图进行更新,但到目前为止还没有成功。

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
    });
  }

因为我进入了无限循环。

如何根据新的props正确更新我的状态。

3个回答

10

您之所以陷入循环,是因为每次组件更新时都设置了新状态。因此,如果状态更新,则意味着组件也会更新,并且您会再次对其进行更新。 因此,您需要防止在状态更改时更新组件。

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

2
根据React文档,第二个参数是prevState。因此,componentDidUpdate(prevProps, prevState, snapshot)。我认为您可能需要重新审查您的逻辑。 - Pranithan T.

2

您需要设置状态,这将触发另一个调用并进行更新,然后再次调用等等。首先必须检查值是否正在更改,然后再设置状态。

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

我建议您使用hooks 在这里查看


0

我之前也遇到过这个问题...你需要做的就是在一些条件下包装 this.setState({..

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接