生命周期
- constructor: 构造函数
- componentWillMount: 组件将要挂载,此时可以访问属性和状态了,可以进行API调用,但是没办法做DOM相关操作
- render
- componentDidMount: 组件已经挂载,可以进行状态更新操作
- componentWillReceiveProps: 组件属性更新了,父组件传递的属性有变化,做相应的响应,第一次不会触发
- shouldComponentUpdate: 组件是否需要更新,返回boolean
- componentWillUpdate: 组件将要更新
- render
- componentDidUpdate: 组件已经更新
- componentWillUnmount: 组件将要卸载时
setState
使用方法
// 方法一
this.setState({a: "b", .....})
// 方法二
// count: 0
this.setState(
(prevState, prevProps) => {
return {count: prevState.count + 1}
},
() => {
console.log(this.state.count) // 1
}
)
注意
- state不能直接改
- setState是异步的
绑定事件的三种方法
// 1. 在constructor绑定
constructor(){
this.handleClick = this.handleClick.bind(this)
}
// 2. jsx绑定
<button onClick={(e) => this.handleClick(e)}></button>
// 3. class里边绑定
this.handleClick = () => { balabala...}
// 注意要是想要传参的话 就得使用第二种方法了