react 生命周期
一、constructor
constructor 参数接受两个参数
可以获取到父组件传下来的props,context,如果你想在constructor构造函数内部使用props或者 context,则需要传入( 在组件其它地方是可以直接接收的),并传入super对象,
只要组件写明了 constructor就需要写上super,否则this指向会错误
constructor(props,context) { super(props,context) console.log(this.props,this.context) // 在内部可以使用props和context }
二、componentWillMount组件将要挂载
1、组件刚经历constructor,初始完数据
2、组件还未进入render,组件还未渲染完成,dom还未渲染
componetWillMount一般用的比较少,更多用在服务端渲染
ajax请求不推荐写在willmount里面
1、如果ajax请求过来的数据是空,那么会影响页面的渲染,可能看到的是空白
2、不利于服务端渲染,在同构的情况下,生命周期会到componentwillMount,
这样使用ajax就会出错
三、componentDidMount组件渲染完成
组件第一次渲染完成,此时dom节点已经生成,可以在这里调用ajax请求,返回数据setstate后组件会重新渲染
四、componentWillReceiveProps(nextProps)
componentWillReiveProps在接受父组件改变后的props需要重新渲染组件时涌动啊的比较多
它需接收一个参数nextProps通过对比nextProps和this.props,将nextProps setState为当前组件的state,从而重新渲染组件
componentWillReceiveProps (nextProps) { nextProps.openNotice !== this.props.openNotice && this.setState({ openNotice:nextProps.openNotice },() => { console.log(this.state.openNotice:nextProps) //将state更新为nextProps,在setState的第二个参数(回调)可以打印出新的state }) }
五、shouldComponentUpdate(nextProps,nextState)\
唯一用于控制组件重新渲染的生命周期,由于在react中,setState以后,state发生变化,组件会进入重新渲染的流程,
因为react父组件的重新渲染会导致其所有子组件的重新渲染,这个时候其实我们是不需要所有子组件都跟着重新渲染的,因此需要在子组件的该生命周期中做判断
六、componentWillUpdate(nextProps,nextState)
shouldComPonentUpdate 返回true以后,组件进入重新渲染的流程,进入componentWillUpdate,这里同样可以拿到nextProps和nextState
七、render函数
render函数会插入jsx生成的dom结构,react会生成一份虚拟dom树,在每一次组件更新时,在此react会通过其diff算法比较更新前后的新旧DOM树,比较以后,找到最小的有差异的DOM节点,并重新渲染
八、componentDidUpdate(preProps,preState)
组件更新完毕后,react只会在第一次初始化成功会进入componentDidMount,之后每次重新选然后都会进入这个生命周期,这里可以拿到prevProps和prevStare,即更新前的props和state
九、componentWillUnmount ()
1.clear你在组建中所有的setTimeout,setInterval
2.移除所有组建中的监听 removeEventListener
3.也许你会经常遇到这个warning
是因为你在组建中的ajax请求返回中setState,而你组件销毁的时候,请求还未完成,因此会报warning
解决办法为
componentDidMount() { this.isMount === true axios.post().then((res) => { this.isMount && this.setState({ // 增加条件ismount为true时 aaa:res }) }) } componentWillUnmount() { this.isMount === false }