类扩展 React.Component 不能在 React 中使用 getInitialState [英] Class extends React.Component can't use getInitialState in React

查看:38
本文介绍了类扩展 React.Component 不能在 React 中使用 getInitialState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm tring the ES6 syntax in React, and write the components like:

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

但是浏览器让我担心:

警告:getInitialState 是在 Loginform 上定义的,一个普通的 JavaScript班级.这仅适用于使用创建的类反应.createClass.你的意思是要定义一个状态属性吗?

Warning: getInitialState was defined on Loginform, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?

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

I can handle it with the traditional syntax var Loginform = React.createClass but what's correct ES6 syntax?

还有一点,我认为在传统语法中 React.createClass 是一个对象,所以其中的函数用逗号分隔,但是对于 extends 类,它需要分号,我不太明白.

Another little thing, I think in traditional syntax React.createClass is an object, so the functions in it is separated by comma, but with the extends class it require semicolon, I don't understand it well.

推荐答案

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

You don't need semicolons or commas between ES6 class method declarations.

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

For ES6 classes, getInitialState has been deprecated in favor of declaring an initial state object in the constructor:

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

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

这篇关于类扩展 React.Component 不能在 React 中使用 getInitialState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆