我正在将 ES6 类与 Babel 一起使用。我有一个 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
.
开发人员谈论 ES6 类支持v0.13.0 发行说明 https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#es6-classes。如果您使用扩展的 ES6 类React.Component
,那么你应该使用constructor()
代替getInitialState
:
该 API 基本上符合您的预期,但 getInitialState 除外。我们认为指定类状态的惯用方法是仅使用简单的实例属性。同样, getDefaultProps 和 propTypes 实际上只是构造函数上的属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)