I read on the React tutorials page that ES6 will use constructor functions to initialize state like this.
export class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
tick() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div onClick={this.tick.bind(this)}>
Clicks: {this.state.count}
</div>
);
}
}
Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };
Then it continues, using ES7 syntax to achieve the same thing.
// Future Version
export class Counter extends React.Component {
static propTypes = { initialCount: React.PropTypes.number };
static defaultProps = { initialCount: 0 };
state = { count: this.props.initialCount };
tick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div onClick={this.tick.bind(this)}>
Clicks: {this.state.count}
</div>
);
}
}
Why is ES7 better then ES6 version or ES5 version.
Thanks
Yes it is here.facebook.github.io/react/blog/2015/01/27/… in the second (ES7) example, the "tick" method could be written tick = () => {...}; or even shorter... tick = () => this.
If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component. The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement.
ES5 uses the Require js module to include a react module or a component. ES6 uses the import module to include a react module or a component. 6. ES5 uses the function keyword along with the return keyword to define a function.
React uses ES6, and you should be familiar with some of the new features like: Classes. Arrow Functions. Variables (let, const, var)
ES7 is better because it enables the following scenarios:
Note: When you define your state by using ES7, you are using Property initializers
feature
References: Class field declarations for JavaScript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With