Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react ES6 component, variables in construct vs state variables

Tags:

reactjs

What is the difference between to define variables in the construct, and use them in the template versus to define inside getInitialState() function?

In ES6 I can forget use getInitialState() and move all on the construct?

Example:

class TodoApp extends Component {  

  constructor() {
    super();
    this.test1 = 'hello this is a test';
    this.state = { // thanks to @Piotr Berebecki, 
                  // i know to define states variable
      test2:'this is state test'
    }
  }
  changeTest () {
    this.state.test2 = 'my new state test';

  }
  render() {


    return (
      <div>
        <button onClick={this.changeTest}>change</button>
        Test:{this.test1}
        <br/>State Test:{this.test2}
      </div>
     );
  }
}


ReactDOM.render(
  <TodoApp />,
  document.getElementById('app')
);
like image 340
stackdave Avatar asked Sep 22 '16 07:09

stackdave


1 Answers

With the ES6 classes syntax we don't use getInitialState. Instead we use: this.state = {} in constructor method. Have a look at the demo here: http://codepen.io/PiotrBerebecki/pen/yagVgA

Also the official React docs (https://facebook.github.io/react/docs/reusable-components.html#es6-classes):

You may also define your React classes as a plain JavaScript class. For example using ES6 class syntax. The API is similar to React.createClass with the exception of getInitialState. Instead of providing a separate getInitialState method, you set up your own state property in the constructor. Just like the return value of getInitialState, the value you assign to this.state will be used as the initial state for your component.

The two snippets below show the difference in syntax.

class TodoApp extends React.Component {
  constructor() {
    super();
    this.state = {
      test2: 1
    };
    this.test3 = 'this is test3';
  }

  changeState() {
    this.setState({
      test2: this.state.test2 + 1
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.changeState.bind(this)}>test2: {this.state.test2}</button>
        <p>test3: {this.test3}</p>
      </div>
    );
  }
}

The above is equivalent to:

var TodoApp = React.createClass({
  getInitialState: function() {
    return {
      test2: 1
    };
  },

  test3: 'this is test3',

  changeState: function() {
    this.setState({
      test2: this.state.test2 + 1
    });    
  },

  render: function() {
    return (
      <div>
        <button onClick={this.changeState}>test2: {this.state.test2}</button>
        <p>test3: {this.test3}</p>
      </div>
    );
  }
});
like image 191
Piotr Berebecki Avatar answered Nov 07 '22 23:11

Piotr Berebecki