When using getDerivedStateFromProps (React) getting error: Cannot read property 'setState' of null

When using getDerivedStateFromProps (React) getting error: Cannot read property 'setState' of null

所以刚刚了解到 componentWillReceiveProps 已被弃用,我们现在需要使用 getDerivedStateFromProps 生命周期方法。 https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

我在下面这样使用它:

class Main extends Component {
  static getDerivedStateFromProps(props) {
    console.log('getDerivedStateFromProps', props);
    const { modal } = props;
    this.setState({ modal });
  }

  constructor(props) {
    super(props);

    this.state = {
      modal: {}
    };
  }

然而它在 setState

上出错

main.js:30 Uncaught TypeError: Cannot read property 'setState' of null at getDerivedStateFromProps (main.js:30)

我在这里错过了什么?

因为getDerivedStateFromProps是一个static函数,所以没有实例(this)。

相反,此功能旨在让您 return 您的状态,而不是使用 this.setState

static getDerivedStateFromProps(props) {
    console.log('getDerivedStateFromProps', props);
    const { modal } = props;
    return { modal };
  }

您在静态方法的上下文中使用它。静态不依赖于 class 的实例,因此 this 不一样。你最好的选择是 return 非静态方法中的模态,然后从那里设置它:D

class Main extends Component {
  static getDerivedStateFromProps(props) {
    console.log('getDerivedStateFromProps', props);
    const { modal } = props;
    return modal;
  }

  constructor(props) {
    super(props);

    this.state = {
      modal: {}
    };
    
    SetModalState(modal)
    {
      this.setState(modal)
    }
  }

除了已经指出的错误(您需要 return 说明),您的实施存在问题,无法正常工作。

您正在尝试 "sync" 一个道具进入本地状态。这是个坏主意,因为 父组件的任何不相关的重新渲染都会破坏本地状态

看来你应该完全删除getDerivedStateFromProps,直接使用道具。在这个例子中你根本不需要本地状态。

要更深入地了解 为什么此模式被打破,以及一些简单的替代方法,请查看 the official React blog post on avoiding deriving state