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

ndb*_*ent 32 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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

它看起来不像getInitialState是被调用,因为我收到了这个错误:Cannot read property 'bar' of null.

ndb*_*ent 61

开发人员在v0.13.0发行说明中讨论了ES6类支持.如果您使用扩展的ES6类React.Component,那么您应该使用a constructor()而不是getInitialState:

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


Des*_*ley 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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)