React 中constructor 做用

react 构造函数只有两个目的

  • 初始化this.state
  • 函数方法绑定到实例。
constructor(props) {
  super(props);
  this.state = { counter: 0 }; //初始化state
  this.handleClick = this.handleClick.bind(this); // 事件绑定
}
初始化state

能够经过属性的方法初始化,Babel将会在后台自动加上constructorreact

class Foo extends Component {
  state = { loading: true };
}
函数方法绑定到实例。

使用es6箭头函数,将不须要将事件在constructor中绑定。es6

在react中能够不使用constructor函数

相关文章
相关标签/搜索