Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

reactjs - Class extends React.Component can't use getInitialState in React

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

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

but the browser throws me a waring about:

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?

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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: ''
    };
  };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...