类扩展了React.Component在React中不能使用getInitialState


77

我正在React中调试ES6语法,并编写如下组件:

export default class Loginform extends React.Component {
    getInitialState() {
        return {
          name: '',
          password: ''
        };
    };
}

但是浏览器使我警惕:

警告:getInitialState是在Loginform(普通的JavaScript类)上定义的。仅使用React.createClass创建的类支持此功能。您是要定义状态属性吗?

我可以使用传统语法来处理它,var Loginform = React.createClass但是正确的ES6语法是什么?

另一件事,我认为传统语法React.createClass是一个对象,因此其中的功能由逗号分隔,但是对于extends需要分号的类,我不太了解。



@FelixKling当然。对不起
Brick Yang

Answers:


150

ES6类方法声明之间不需要分号或逗号。

对于ES6类,getInitialState已弃用,而在构造函数中声明初始状态对象:

export default class Loginform extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      name: '',
      password: ''
    };
  };
}

有了这个,当时console.log(this.state.name),它会引发一个错误Cannot read property 'state' of null
Brick Yang

4
您想在哪里打电话?在ES6中,类this不是自动绑定的,这可能是问题的一部分:facebook.github.io/react/blog/2015/01/27/…–
最大值

2
引用链接的文章中提到:“ ReactcreateClass功能提供的好处之一是它自动将您的方法绑定到组件实例。例如,这意味着在click回调内this将绑定到组件。转移到ES6类,我们必须处理这个绑定自己的阵营团队建议在构造预绑定。newmediacampaigns.com/blog/...
精读Antonakos

1
我有点喜欢它与ES5一样的方式-和getInitialState()
Alexander Mills

7

ES6示例:state,defaultProps,propTypes

import React from 'react'
import ReactDom from 'react-dom';
export default class Item extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            check:false,
        };
        this.click=this.click.bind(this);
    }
    click(){
       this.setState({check:true});
    }
    render(){
        const text=this.state.check?'yes':'no';
        return(<div onClick={this.click}>{this.props.name} : <b>{text}</b></div>)
    }

}

Item.defaultProps={
    comment:"default comment",
};
Item.propTypes={
    name:React.PropTypes.string.isRequired,
};

1

如果我们使用类字段,则以下工作正常。

state = {
      name: '',
      password: ''
}

可以代替

constructor(props, context) {
    super(props, context);

    this.state = {
      name: '',
      password: ''
    };
  };
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.