【问题标题】:Class extends React.Component can't use getInitialState in React类扩展 React.Component 不能在 React 中使用 getInitialState
【发布时间】:2016-01-31 12:54:28
【问题描述】:

我正在研究 React 中的 ES6 语法,并编写如下组件:

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

但浏览器让我警惕:

警告:getInitialState 是在 Loginform 上定义的,这是一个纯 JavaScript 班级。这仅支持使用创建的类 React.createClass。您的意思是定义一个 state 属性吗?

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

另外一个小东西,我觉得在传统语法中React.createClass是一个对象,所以里面的函数用逗号隔开,但是extends这个类需要分号,我不是很懂。

【问题讨论】:

标签: reactjs


【解决方案1】:

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的错误
  • 你想在哪里调用它?在 ES6 类中,this 不会自动绑定,这可能是问题的一部分:facebook.github.io/react/blog/2015/01/27/…
  • 引用链接文章:“React 的createClass 功能提供的一个优点是它自动将您的方法绑定到组件实例。例如,这意味着在单击回调this 将绑定到组件。随着迁移到 ES6 类,我们必须自己处理此绑定。React 团队建议在构造函数中进行预绑定。" newmediacampaigns.com/blog/…
  • 我有点喜欢 ES5 的方式 - 和 getInitialState()
【解决方案2】:

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,
};

【讨论】:

    【解决方案3】:

    如果我们使用类字段,以下是有效的。

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

    这个可以代替

    constructor(props, context) {
        super(props, context);
    
        this.state = {
          name: '',
          password: ''
        };
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-15
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      相关资源
      最近更新 更多