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')
);
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/yagVgAAlso the official React docs (https://facebook.github.io/react/docs/reusable-components.html#es6-classes):
The two snippets below show the difference in syntax.
The above is equivalent to: