当使用getDerivedStateFromProps(React)获取错误时:无法读取null的属性'setState'

Leo*_*ban 0 javascript reactjs getderivedstatefromprops

所以刚刚学会了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: {}
    };
  }
Run Code Online (Sandbox Code Playgroud)

但是它出错了 setState

在此输入图像描述

main.js:30未捕获的TypeError:无法在getDerivedStateFromProps(main.js:30)读取null的属性'setState'

我在这里错过了什么?

Jam*_*xon 8

因为getDerivedStateFromProps是一个static函数,所以没有instance(this).

相反,此功能的设计使您可以返回状态而不是使用状态this.setState.

static getDerivedStateFromProps(props) {
    console.log('getDerivedStateFromProps', props);
    const { modal } = props;
    return { modal };
  }
Run Code Online (Sandbox Code Playgroud)


Dan*_*mov 7

除了已经指出的错误(您需要返回状态)之外,您的实现还有问题,无法正常工作。

您正在尝试将道具“同步”到本地状态。这是一个坏主意,因为父组件的任何不相关的重新渲染都将破坏本地状态

看来您应该完全删除getDerivedStateFromProps,而直接使用道具。在此示例中,您根本不需要本地状态。

要更深入地了解为什么会破坏这种模式以及一些简单的替代方法,请查看有关避免推导状态的官方React博客文章