首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用getDerivedStateFromProps (React)时出现错误:无法读取null的属性'setState‘

使用getDerivedStateFromProps (React)时出现错误:无法读取null的属性'setState‘
EN

Stack Overflow用户
提问于 2018-06-01 04:49:42
回答 3查看 7.4K关注 0票数 1

我刚刚了解到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未捕获TypeError:无法在getDerivedStateFromProps (main.js:30)读取null的属性“”setState“”

这里我漏掉了什么?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-06-01 04:51:57

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

相反,此函数的设计目的是让您返回状态,而不是使用this.setState

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

Stack Overflow用户

发布于 2018-06-10 22:48:56

除了前面已经指出的错误(你需要返回状态),你的实现是错误的,不能正常工作。

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

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

要更深入地了解为什么打破了这种模式,以及一些简单的替代方案,请查看

票数 7
EN

Stack Overflow用户

发布于 2018-06-01 04:52:19

您可以在静态方法的上下文中使用它。静态不依赖于类的实例,因此这是不同的。最好的方法是在非静态方法中返回modal,然后从那里设置它: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)
    }
  }

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50632573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档