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