挂载中(只执行一次)
以下方法在组件实例正被创建和插入到DOM中时调用
constructor()一般用于初始化state和方法的this绑定
componentWillMount()
render()
componentDidMount() 一般用于建立订阅,副作用和ajax获取数据
更新中
属性或者状态的改变会触发更新,以下方法将在组件重绘中被调用
componentWillReceiveProps() 用于处理挂载的组件属性变化引起的状态改变,通过比较来判定是否使用setstate方法。
shouldComponentUpdate() 若返回false则不处罚以下方法,默认返回true
componentWillUpdate() 该方法内部不能调用setstate方法
render()
componentDidUpdate()
移除中
该方法在组件正被移除中被调用
componentWillUnmount()
事实胜于雄辩,下面来一段代码,让你了解所有方法的执行顺序,同时里面也包含了不可控组件ref中方法的执行时机
class App extends React.Component{ constructor(props){ super(props); this.state={ num:0 } this.changeName = this.changeName.bind(this) } componentWillMount(){ console.log('willmount') } componentDidMount(){ console.log('didMount') } componentWillReceiveProps(nextprops){ console.log('willrecieve') } shouldComponentUpdate(){ console.log('shouldupdate') return true } componentWillUpdate(){ console.log('willupdate') } componentDidUpdate(){ console.log('didiupdate') } componentWillUnmount(){ console.log('unmount') } changeName(){ let num = this.state.num+1 this.setState({ num }) } render(){ console.log('render') return( <div onClick={this.changeName} ref={div=>{console.log(div)}}> {this.state.num} </div> ) } }
文中没有提到使用场景的方法不推荐使用,因为基本所有的操作都可以被说明用途的替代掉,当然抛出一定状态下,eg:更新完成之后我要alert一下,如果存在什么问题可以留言,我会及时回复
参考:https://reactjs.org/docs/react-component.html#constructor