react生命周期方法(重新整理)

859 阅读2分钟

react生命周期方法

  • Mounting(加载阶段)

    • constructor():可初始化state
    • componentWillMount():组件加载时只调用,以后组件更新不调用,整个生命周期只调用一次,此时可以修改state
    • render():创建虚拟dom,进行diff算法,更新dom树都在此进行
    • componentDidMount():组件渲染之后调用,只调用一次
  • Updating(更新阶段:涉及5个钩子函数)

    • componentWillReceivePorps(nextProps):组件加载时不调用,组件接受新的props时调用
    • shouldComponentUpdate(nextProps, nextState):组件接收到新的props或者state时调用,return true就会更新dom(使用diff算法更新),return false能阻止更新(不调用render)
    • componentWillUpdata(nextProps, nextState):组件加载时不调用,只有在组件将要更新时才调用,此时可以修改state
    • render():react最重要的步骤,创建虚拟dom,进行diff算法,更新dom树都在此进行
    • componentDidUpdate():组件加载时不调用,组件更新完成后调用
  • Unmounting(卸载阶段:涉及1个钩子函数)

    • componentWillUnmount():组件渲染之后调用,只调用一次

react生命周期方法(未来)

  • static getDerivedStateFromProps(props, state)

    • 组件每次被render的时候,包括在组件构建之后(虚拟dom之后,实际dom挂载之前),每次获取新的props或state之后;每次接收新的props之后都会返回一个对象作为新的state,返回null则说明不需要更新state;配合componentDidUpdate,可以覆盖componentWillReceiveProps的所有用法。
    • 代替(componentWillMount()componentWillReceivePorps(nextProps)
  • getSnapshotBeforeUpdate(prevProps, prevState)

    • 触发时间: update发生的时候,在render之后,在组件dom渲染之前;返回一个值,作为componentDidUpdate的第三个参数;配合componentDidUpdate, 可以覆盖componentWillUpdate的所有用法
    • 代替componentWillUpdata(nextProps, nextState)
  • Error Handling(错误处理)

    • componentDidCatch(error,info)

生命周期总结

  1. React16新的生命周期弃用了componentWillMount、componentWillReceivePorps,componentWillUpdate
  2. 新增了getDerivedStateFromProps、getSnapshotBeforeUpdate来代替弃用的三个钩子函数(componentWillMount、componentWillReceivePorps,componentWillUpdate
  3. React16并没有删除这三个钩子函数,但是不能和新增的钩子函数(getDerivedStateFromProps、getSnapshotBeforeUpdate)混用,React17将会删除componentWillMount、componentWillReceivePorps,componentWillUpdate
  4. 新增了对错误的处理(componentDidCatch