react 构造函数只有两个目的
- 初始化this.state
- 函数方法绑定到实例。
constructor(props) {
super(props);
this.state = { counter: 0 }; //初始化state
this.handleClick = this.handleClick.bind(this); // 事件绑定
}
初始化state
可以通过属性的方法初始化,Babel将会在后台自动加上constructor
class Foo extends Component {
state = { loading: true };
}
函数方法绑定到实例。
使用es6箭头函数,将不需要将事件在constructor中绑定。
在react中可以不使用constructor