-
Notifications
You must be signed in to change notification settings - Fork 6
Open
Description
题目:
请写出 React 组件的生命周期函数分别有哪些,并简单介绍下各自的作用。
参考答案:
挂载阶段
componentWillMount组件挂载到 DOM 前render组件渲染。视图的 JSX 就写在这个函数里componentDidMount组件挂载到 DOM 后。可以访问到 DOM 对象了,一些初始化的 AJAX 请求适合在此阶段发送
更新阶段
componentWillReceiveProps组件接收到新状态 propsshouldComponentUpdate类似于一个拦截器,控制组件是否更新,可以在此阶段一定程度上优化组件,返回 true 表示继续更新,返回 false 则中断组件 rendercomponentWillUpdate调用 render 方法更新组件前componentDidUpdate组件更新后。可以操作更新后组件的 DOM 了
卸载阶段
componentWillUnmount组件卸载前。可以在这里执行一些清理工作,如清除组件中的定时器等
上述便是 React v16.0 前的生命周期函数,但在 v16.3 后玩法变了,除了 shouldComponentUpdate,其他在render 函数之前的所有函数(componentWillMount,componentWillReceiveProps,componentWillUpdate)都被新增加的 getDerivedStateFromProps 替代,被替代的生命周期函数会在下一个大版本(也就是React v17) 更新时彻底废弃。React v16.3 还引入了一个新的声明周期函数getSnapshotBeforeUpdate,所以最新的生命周期函数列表变成了这样(v16.4):
挂载阶段
static getDerivedStateFromProps在组件创建时和更新 render 方法之前调用,返回一个对象来更新状态,或者返回 null 来不更新任何内容。注意:这是一个静态方法。- render
componentDidMount
更新阶段
shouldComponentUpdategetSnapshotBeforeUpdate被调用于render之后,可以读取但无法使用 DOM 的时候,在此阶段可以从 DOM 捕获一些信息(例如滚动位置)。此生命周期返回的任何值都将作为参数传递给componentDidUpdatecomponentDidUpdate
卸载阶段
componentWillUnmount
Metadata
Metadata
Assignees
Labels
No labels