【问题标题】:Why is getInitialState not being called for my React class?为什么我的 React 类没有调用 getInitialState?
【发布时间】:2015-07-29 19:17:30
【问题描述】:

我正在使用带有 Babel 的 ES6 类。我有一个看起来像这样的 React 组件:

import { Component } from 'react';

export default class MyReactComponent extends Component {
  getInitialState() {
    return {
      foo: true,
      bar: 'no'
    };
  }

  render() {
    return (
      <div className="theFoo">
        <span>{this.state.bar}</span>
      </div>
    );
  }
}

看起来 getInitialState 没有被调用,因为我收到了这个错误:Cannot read property 'bar' of null

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    开发人员在Release Notes for v0.13.0 中讨论了 ES6 类支持。如果你使用扩展 React.Component 的 ES6 类,那么你应该使用 constructor() 而不是 getInitialState

    除了 getInitialState 之外,API 大部分都是您所期望的。我们认为指定类状态的惯用方法是只使用一个简单的实例属性。同样,getDefaultProps 和 propTypes 实际上只是构造函数上的属性。

    【讨论】:

    • 我花了几分钟才弄清楚这一点,所以我想将其作为问答分享,因为我在 Google 上找不到任何内容。
    • 是的,getInitialState 在这一点上只是任何通用函数
    【解决方案2】:

    伴随 Nathans 回答的代码:

    import { Component } from 'react';
    
    export default class MyReactComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          foo: true,
          bar: 'no'
        };
      }
    
      render() {
        return (
          <div className="theFoo">
            <span>{this.state.bar}</span>
          </div>
        );
      }
    }
    

    【讨论】:

      【解决方案3】:

      稍微解释一下它的含义

      getDefaultProps 和 propTypes 实际上只是构造函数上的属性。

      “在构造函数上”位是奇怪的措辞。在普通的 OOP 语言中,它只是意味着它们是“静态类变量”

      class MyClass extends React.Component {
          static defaultProps = { yada: "yada" }
          ...
      }
      

      MyClass.defaultProps = { yada: "yada" }
      

      您也可以在类中引用它们,例如:

      constructor(props) {
          this.state = MyClass.defaultProps;
      }
      

      或者任何你声明为静态类变量的东西。我不知道为什么 anywhere 没有在线谈论 ES6 类:?

      see the docs.

      【讨论】:

        猜你喜欢
        • 2014-10-13
        • 1970-01-01
        • 2015-08-20
        • 2019-05-08
        • 2017-06-14
        • 2012-01-30
        • 2022-12-15
        • 2014-04-08
        • 2018-07-11
        相关资源
        最近更新 更多