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
301 views
in Technique[技术] by (71.8m points)

reactjs - React constructor ES6 vs ES7

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

question from:https://stackoverflow.com/questions/35662932/react-constructor-es6-vs-es7

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

1 Answer

0 votes
by (71.8m points)

ES7 is better because it enables the following scenarios:

  • Where declarative interpretation of expectations are useful. Some examples include editors so that they can make use of this info for typeaheads/inference, TypeScript/Flow can make use of this to allow their users to express intentions about the shapes of their classes
  • Allowing general users to use this for just human-readable documentation about properties separate from potentially complex initialization logic
  • Possibly allow VMs to pre-emptively optimize objects created from a class with some of these hints on them.

Note: When you define your state by using ES7, you are using Property initializers feature

References: Class field declarations for JavaScript


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

...