Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 49 期(主流框架-React):生命周期函数 #52

Open
wingmeng opened this issue Jul 3, 2019 · 0 comments
Open

第 49 期(主流框架-React):生命周期函数 #52

wingmeng opened this issue Jul 3, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jul 3, 2019

题目:

请写出 React 组件的生命周期函数分别有哪些,并简单介绍下各自的作用。


参考答案:

挂载阶段

  1. componentWillMount 组件挂载到 DOM 前
  2. render 组件渲染。视图的 JSX 就写在这个函数里
  3. componentDidMount 组件挂载到 DOM 后。可以访问到 DOM 对象了,一些初始化的 AJAX 请求适合在此阶段发送

更新阶段

  1. componentWillReceiveProps 组件接收到新状态 props
  2. shouldComponentUpdate 类似于一个拦截器,控制组件是否更新,可以在此阶段一定程度上优化组件,返回 true 表示继续更新,返回 false 则中断组件 render
  3. componentWillUpdate 调用 render 方法更新组件前
  4. componentDidUpdate 组件更新后。可以操作更新后组件的 DOM 了

卸载阶段

  1. componentWillUnmount 组件卸载前。可以在这里执行一些清理工作,如清除组件中的定时器等

上述便是 React v16.0 前的生命周期函数,但在 v16.3 后玩法变了,除了 shouldComponentUpdate,其他在render 函数之前的所有函数(componentWillMountcomponentWillReceivePropscomponentWillUpdate)都被新增加的 getDerivedStateFromProps 替代,被替代的生命周期函数会在下一个大版本(也就是React v17) 更新时彻底废弃。React v16.3 还引入了一个新的声明周期函数getSnapshotBeforeUpdate,所以最新的生命周期函数列表变成了这样(v16.4):

挂载阶段

  1. static getDerivedStateFromProps 在组件创建时和更新 render 方法之前调用,返回一个对象来更新状态,或者返回 null 来不更新任何内容。注意:这是一个静态方法。
  2. render
  3. componentDidMount

更新阶段

  1. shouldComponentUpdate
  2. getSnapshotBeforeUpdate 被调用于render之后,可以读取但无法使用 DOM 的时候,在此阶段可以从 DOM 捕获一些信息(例如滚动位置)。此生命周期返回的任何值都将作为参数传递给 componentDidUpdate
  3. componentDidUpdate

卸载阶段

  1. componentWillUnmount

React v16.3之后的组件生命周期函数
React Fiber是什么
React 生命周期函数图谱

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant