Javascript 为什么我的React类没有调用getInitialState?
我和巴贝尔一起使用ES6课程。我有一个React组件,看起来像这样:Javascript 为什么我的React类没有调用getInitialState?,javascript,reactjs,Javascript,Reactjs,我和巴贝尔一起使用ES6课程。我有一个React组件,看起来像这样: import { Component } from 'react'; export default class MyReactComponent extends Component { getInitialState() { return { foo: true, bar: 'no' }; } render() { return ( <div c
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>
);
}
}
从'react'导入{Component};
导出默认类MyReactComponent扩展组件{
getInitialState(){
返回{
傅:是的,
酒吧:“不”
};
}
render(){
返回(
{this.state.bar}
);
}
}
它看起来不像是调用了
getInitialState
,因为我遇到了这样的错误:无法读取null的属性“bar”
开发人员在。如果使用扩展了React.Component
的ES6类,则应使用constructor()
而不是getInitialState
:
除了getInitialState之外,API基本上是您所期望的。我们认为,指定类状态的惯用方法是只使用一个简单的实例属性。同样,getDefaultProps和PropType实际上只是构造函数上的属性
内森回答的代码:
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>
);
}
}
从'react'导入{Component};
导出默认类MyReactComponent扩展组件{
建造师(道具){
超级(道具);
此.state={
傅:是的,
酒吧:“不”
};
}
render(){
返回(
{this.state.bar}
);
}
}
对其含义进行一点扩展
getDefaultProps和PropType实际上只是构造函数上的属性
“on the constructor”位的措辞很奇怪。在普通的OOP语言中,这仅仅意味着它们是“静态类变量”
或
您也可以在类中引用它们,如:
constructor(props) {
this.state = MyClass.defaultProps;
}
或者使用任何声明为静态类变量的内容。我不知道为什么网上没有提到ES6课程:
.我花了几分钟的时间才弄明白这一点,所以我想把它作为问答分享,因为我在Google上找不到任何东西。是的,getInitialState在这一点上只是任何通用函数
MyClass.defaultProps = { yada: "yada" }
constructor(props) {
this.state = MyClass.defaultProps;
}