React 组件生命周期
superman66 opened this issue · comments
React Component 生命周期
每个 Component 都提供了一些生命周期函数钩子。生命周期方法包含前缀will
表示该钩子函数会在该生命周期发生之前调用;
包含前缀did
表示该钩子函数会在该生命周期发生之后调用。
先看一张 component 生命周期的图片:
上图就是 React Component 的生命周期,从 组件挂载(mount)到组件销毁(unmount)的过程。
React Component 的生命周期可以分为下面几类:
Mounting(挂载)
下面这些方法将会在 component 实例被创建和插入到DOM后调用。
constructor()
componentWillMount()
render()
componentDidMount()
Updating
props 或者 state 的变化都会导致更新。下面这些方法会在 component 重新渲染时调用。
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
Unmounting
该方法将会在 component 从DOM中移除时调用
componentWillUnmount()
上述的过程便是 React Component 的生命周期执行顺序,依次从上至下执行。
接下来我们就来一一详解各个生命周期及其的使用场景。
生命周期
componentWillMount()
componentWillMout()
是在组件挂载(mount) 之前被调用。因为它是在render()
方法之前被调用。在该方法中进行同步 setState
不会导致重绘。
componentWillMount()
是唯一一个在服务器端渲染调用的生命周期钩子,不过一般建议用 constructor()
是否可以使用setState()
: 可以
componentDidMount()
componentDidMount()
在组件挂载之后立即执行。适用于:
- 需要初始化 DOM 节点的操作
- AJAX 请求;
在该钩子函数里面,可以使用 setState()
,但是会触发重新渲染(re-render).
是否可以使用setState()
: 可以
componentWillReceiveProps(nextProps)
该钩子函数将会在已挂载组件(mounted component)接收到新的 props 之前调用。适用于:
- 更新 state的值(比如重置)
- 比较 this.props 和 nextProps
需要注意的是,即使 Props 没有发生变化,React 也有可能会调用该钩子函数。所以如果你想要真正处理 Props 的变化,要记得比较当前 props 和nextProps.
出现这种情况的场景:当父组件导致了该组件的 re-render 时,就会出现上述的情况。
是否可以使用setState()
: 可以
shouldComponentUpdate(nextProps, nextState)
当组件接收到新的 Props 或者 state时,要进行 rendering之前会调用 shouldComponentUpdate()
。该钩子函数用于告诉 React 组件是否需要重新渲染。
shouldComponentUpdate()
默认返回 true
。
shouldComponentUpdate()
在两种情况下不会被调用:
- 初始化渲染
- 使用了
forceUpdate()
情况下
但是当 shouldComponentUpdate()
返回 false
的时候,此时 state 发生改变,并不能阻止 child component 进行重新渲染。
但是一旦 shouldComponentUpdate()
返回 false
,这就意味着 componentWillUpdate()
、 render()
和 componentDidUpdate()
将不再执行。
componentWillUpdate()
state or props 更新后re-render之前调用。
不能在这里调用 setState
,如果需要设置 state,应该在 componentWillReceiveProps()
中调用 setState()
.
是否可以使用setState()
: 不可以
componentDidUpdate()
在组件更新之后马上调用。在该钩子函数内,你可以:
- 操作 DOM
- 发起网络请求
是否可以使用setState()
: 可以
componentWillUnmount()
在组件卸载和销毁前调用。在该钩子函数内可以做一些清除工作,比如:
- 取消定时器
- 取消网络请求
- 解绑 DOM 事件
是否可以使用setState()
: 不可以
componentWillMount()在装配发生前被立刻调用。其在render()之前被调用,因此在这方法里同步地设置状态将不会触发重渲。
请问,图例用什么画图软件制作的?
我也不知道,这张图是网上找的。
@superman66 Thanks for the reply
关于componentwillmount说错了
componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.
—— 官方文档关于componentwillmount的介绍
在componentwillmount进行同步setState不会导致重绘
@millionbug @sincerexie 多谢你们指出错误所在。