Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我的React类没有调用getInitialState?_Javascript_Reactjs - Fatal编程技术网

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

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

我和巴贝尔一起使用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>
    );
  }
}
从'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;
}