React生命周期函数理解

一、组件挂载阶段

  1. componentWillMount() 

  该方法在首次渲染之前调用,在一个组件挂载到卸载的过程中,仅仅执行这一次。该函数内可以state初始化的工作,与constructor的作用类似。这里也是在render方法调用前最后一次修改state的方法。

  这里不建议使用Ajax获取接口数据,因为是异步的,所以在接下来的第一次render中根本接收不到响应数据。

  willMount中setState还是会多一次渲染

  2. render()

  该方法创建一个虚拟dom,表示组件的输出。(输出可以应用到react-dom,react-native)

  3.componentDidMount()

  该方法调用时,表明已经渲染出真实的dom,可以在该方法中获取任意节点。

二、组件更新阶段

  2.1 父组件状态改变,触发子组件更新(简单说是获取到了新的props)

    2.1.1 componentWillReceiveProps(nextProps)

    当父级组件state或者props发生改变时,子组件会调用该方法。这里的nextProps和this.props需要我们自己判断是否相同来做出相应的操作。比如根据新的props来setState

    2.1.2 shouldComponentUpdate(nextProps, nextState) 

    当确定组件的props或者state的某种改变不需要重新渲染时,可以通过这个方法返回false来阻止渲染。

    2.1.3 componentWillUpdate(nextProps, nextState) 

    组件得到新的props或者state时,在render前调用该函数。(不要在此方法中更新state)

    如果需要相应props的改变时,可以在componentWillReceiveProps中做出响应操作

    2.1.4 render

    2.1.5 componentDidUpdate(prevProps, prevState)

    可以对更新后的dom进行操作

  2.2 组件内部状态更新

    少了componentWillMount,其他与上面一致

三、卸载

  componentWillUnmount()

  清除定时器,网络请求等

引用:https://moeover.com/2017/01/17/understand-react-lifecycle.html

猜你喜欢

转载自www.cnblogs.com/iszhangjin/p/11442340.html