React生命周期LifeCycle
React 生命周期主要包括三个阶段:初始化阶段,更新阶段,销毁阶段
初始化阶段
执行顺序 constructor
-> getDerivedStateFromProps
或者 componentWillMount
-> render
-> componentDidMount
constructor执行
constructor
在组件初始化的时候只会执行一次
通常它用于做这两件事
- 初始化函数内部
state
- 绑定函数
constructor(props) {
console.log('进入构造器');
super(props)
this.state = { count: 0 }
}
现在我们通常不会使用 constructor
属性,而是改用类加箭头函数的方法,来替代 constructor
例如,我们可以这样初始化 state
state = {
count: 0
};
static getDerivedStateFromProps 执行 (新钩子)
这个是 React 新版本中新增的2个钩子之一,据说很少用。
getDerivedStateFromProps
在初始化和更新中都会被调用,并且在 render 方法之前调用,它返回一个对象用来更新 stategetDerivedStateFromProps
是类上直接绑定的静态(static)方法,它接收两个参数 props 和 state- props 是即将要替代 state 的值,而 state 是当前未替代前的值
state
的值在任何时候都取决于传入的 props
,不会再改变
可以说,这个生命周期的功能实际上就是将传入的props映射到state上面。
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritesite: "runoob"};
}
//拿到变化后的props和state
static getDerivedStateFromProps(props, state) {
return {favoritesite: props.favsite };
}
render() {
return (
<h1>我喜欢的网站是 {this.state.favoritesite}</h1>
);
}
}
ReactDOM.render(<Header favsite="Google"/>, document.getElementById('root'));
componentWillMount 执行(即将废弃)
如果存在 getDerivedStateFromProps
和 getSnapshotBeforeUpdate
就不会执行生命周期componentWillMount
。
该方法只在挂载的时候调用一次,表示组件将要被挂载,并且在 render
方法之前调用。
这个方法在 React 18版本中将要被废弃,官方解释是在 React 异步机制下,如果滥用这个钩子可能会有 Bug
render执行
render()
方法是组件中必须实现的方法,用于渲染 DOM ,但是它不会真正的操作 DOM,它的作用是把需要的东西返回出去。
实现渲染 DOM 操作的是 ReactDOM.render()
注意:避免在
render
中使用setState
,否则会死循环
componentDidMount 执行
componentDidMount
的执行意味着初始化挂载操作已经基本完成,它主要用于组件挂载完成后做某些操作
这个挂载完成指的是:组件插入 DOM tree
更新阶段
getDerivedStateFromProps 执行
这个老熟人了,在上面初始化阶段的内容时就提到了他,我们在之前也提到了更新时他也会被调用
shouldComponentUpdat 执行
shouldComponentUpdate()
在组件更新之前调用,可以通过返回值来控制组件是否更新,允许更新返回 true
,反之不更新
举例:
如果你的组件只有当
props.color
或者state.count
的值改变才需要更新时,你可以使用shouldComponentUpdate
来进行检查:
class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
render 执行
在控制是否更新的函数中,如果返回 true
才会执行 render
,得到最新的 React element
getSnapshotBeforeUpdate 执行
在最近一次的渲染输出之前被提交之前调用,也就是即将挂载时调用
相当于淘宝购物的快照,会保留下单前的商品内容,在 React 中就相当于是 即将更新前的状态
它可以使组件在 DOM 真正更新之前捕获一些信息(例如滚动位置),此生命周期返回的任何值都会作为参数传递给
componentDidUpdate()
。如不需要传递任何值,那么请返回 null
componentDidUpdate 执行
组件在更新完毕后会立即被调用,首次渲染不会调用
销毁阶段
componentWillUnmount 执行
在组件即将被卸载或销毁时进行调用。
总结
初始化
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
更新
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
销毁
componentWillUnmount()