React 替换 componentWillReceiveProps

fef*_*efe 4 updates deprecated prop reactjs

在我的子组件中使用以下方法更新道具更改状态,效果很好

  componentWillReceiveProps(nextProps) {
    // update original states
    this.setState({
      fields: nextProps.fields,
      containerClass: nextProps.containerClass
    });
  }
Run Code Online (Sandbox Code Playgroud)

我越来越 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
    });
  }
Run Code Online (Sandbox Code Playgroud)

因为我陷入了无限循环。

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

Sho*_*ili 7

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

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

  • 根据 [React doc](https://reactjs.org/docs/react-component.html#componentdidupdate),第二个参数是 prevState。所以,`componentDidUpdate(prevProps, prevState, snapshot)`。我想你可以回顾一下你的逻辑 (2认同)