美文网首页
React 生命周期

React 生命周期

作者: 芝麻香油 | 来源:发表于2017-11-13 21:38 被阅读0次

从印度回来后学了 React 那么久,居然从来没有仔细去看过 React 的生命周期。还是今天被问到的时候,才知道了。

犹记得有那么一段时间,手机的锁屏还是


当年的手机锁屏.png

然而今天并没有完整的说出这所有的过程(按照顺序),分分钟打脸了。

事实上,React 的生命周期主要分为三个过程:装载过程,更新过程,以及卸载过程。

装载过程

把组件第一次在 DOM 树种渲染的过程

image.png
  • getDefaultProps()
    用来设置组件属性的默认值,在组件被建立时就会立即调用,所有实例都可以共享这些属性。
  • getInitialState()
    用于定义初始状态。
  • componentWillMount()
    只在初始化时候被调用一次,可以使用 setState 方法,会立即更新 state,然后会进行 render
  • render()
    render 中使用 setState 方法会报错。若其中包含其他的子组件,那么子组件的生命周期才开始进行
  • componentDidMount()
    在子组件也都加载完毕后执行,DOM 渲染完成,此时就可以操作 DOM 了。但是由于 React 中的 DOM 是虚拟 DOM,因此不推荐操作 DOM。

更新过程

组件被重新渲染的过程

更新过程分为 props 发生改变和 state 发生改变

  1. props 发生改变
  • componentWillReceiveProps(nextProps)
  • shouldComponentUpdate(nextProps, nextState)
  • componentWillUpdate(nextProps, nextState)
  • render()
  • componentDidUpdate(prevProps, prevState)
  1. state 发生改变
  • shouldComponentUpdate(nextProps, nextState)
  • componentWillUpdate(nextProps, nextState)
  • render()
  • componentDidUpdate(prevProps, prevState)

其中,

  • shouldComponentUpdate(nextProps, nextState)
    该方法决定了一个组件什么时候不需要渲染,返回一个布尔值。告诉 React 这个组件在这次更新过程中是否要继续。
    shouldComponentUpdate(nextProps, nextState)

通常在该方法中比较当前的 state,props 和 nextState,nextProps 来进行比较。返回 true 或 false 来渲染组件,优化性能

  • componentWillUpdate(nextProps, nextState)
    在 state 改变或 shouldComponentUpdate 返回 true 后出发

  • componentDidUpdate(prevProps, prevState)
    会等子组件也都更新完后才触发

卸载过程

组件从 DOM 中删除的过程

image.png
  • componentWillUnmount()
    该方法与 componentDidMount 有关,例如:在 componentDidMount 中用非 React 的方法创造一些 DOM 元素,如果不管可能会造成内存泄漏,因此需要 componentWillUnmount 中把这些创造的 DOM 元素清理掉。

注意
不要在 shouldCompoentUpdate、componentWillUpdate、componentDidUpdate,以及 render 中使用 setState。


The End ~
21 天写作训练,第 8 天 ing

相关文章

  • React概念图

    React概念图 React组件生命周期概念图 参考文档:React入门教程 组件生命周期React:组件生命周期...

  • React基础篇之组件的生命周期

    引出生命周期 react生命周期(旧) react生命周期(新) getSnapshotBeforeUpdate的...

  • React生命周期

    React v16.0前的生命周期 React v16.4+ 的生命周期图 React v16.9后这些生命周期钩...

  • React v16 生命周期

    React 16 生命周期 React 16.3 新增的生命周期方法 逐渐废弃的生命周期方法: 一般将生命周期分成...

  • 学习并实现react (4)

    实现生命周期 生命周期介绍 React 生命周期图 React 子组件在父组件下的生命周期流程 实现 compon...

  • React面试题 整理脑图

    react基础 React生命周期 react-router react进阶 react Hooks redux 其他

  • react/vue常见问题整理

    一、react 1. react生命周期 react 16生命周期相对于15的变化:componentWillMo...

  • React 组件生命周期

    组件生命周期 参考阅读: component-lifecycle react组件生命周期过程说明 react 组件...

  • 《深入React技术栈》学习笔记Ⅲ

    以下的生命周期都是在 React 15 的生命周期, React 16 的生命周期 API 已经发生变化。Reac...

  • React总结

    [toc] 1.React组件生命周期 1.1 生命周期图 组件的生命周期的图如下: 具体可参考React 组件生...

网友评论

      本文标题:React 生命周期

      本文链接:https://www.haomeiwen.com/subject/mertvxtx.html