为什么没有为我的React类调用getInitialState?

时间:2015-07-29 19:17:31

标签: javascript reactjs

我正在使用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

3 个答案:

答案 0 :(得分:61)

开发人员在Release Notes for v0.13.0中讨论ES6类支持。如果您使用的是扩展React.Component的ES6类,则应使用constructor()代替getInitialState

  

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

答案 1 :(得分:31)

伴随着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>
    );
  }
}

答案 2 :(得分:2)

进一步扩大意义

  

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

构造函数&#34;&#34;有点奇怪的措辞。在普通的OOP语言中,它只是意味着它们是静态类变量&#34;

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

MyClass.defaultProps = { yada: "yada" }

你也可以在课堂上引用它们,如:

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

或与您声明为静态类变量的任何内容。我不知道为什么在ES6课程中没有在网上谈论任何地方:?

see the docs

相关问题