getDerivedStateFromProps
2024年03月06日
一、认识
getDerivedStateFromProps
: 是一个静态的方法,不能访问到组件的实例, 它更趋向于纯函数。执行时机: 在初始化和更新阶段, 接受父组件的即将更新的 props
数据以及上一个状态的 state
, 可以对 props
、state
进行格式化, 过滤等操作, 加一些限制条件, 返回值将作为新的 state
合并到 state
中, 供给视图渲染层消费, 返回 null
表示 state
状态不需要更新。 合并的 state
可以供 shouldComponentUpdate
使用,防止无用的 state
更新。getDerivedStateFromProps
方法从源码中就能够体会到 React
对该生命周期定义为取缔 componentWillMount
和 componentWillReceiveProps
。用于:
-
代替
componentWillMount
和componentWillReceiveProps
-
组件初始化或者更新时,将
props
映射到state
-
返回值与
state
合并完,可以作为shouldComponentUpdate
第二个参数newState
,可以判断是否渲染组件
二、语法
static getDerivedStateFromProps(newProps,prevState) {
console.log(newProps) // 父组件传递数据 props
console.log(prevState) // 组件状态
console.log(this) // undefined
return {type:"子组件"} // 返回值作为新的 state 合并到 state 中
}
-
nextProps
: 父组件新传递的props
-
prevState
: 组件在此次渲染前待更新的state
三、场景
3.1 子组件通过getDerivedStateFromProps
将props
与自己的state
合并,成为新的state
**
static getDerivedStateFromProps(newProps, prevState) {
return { ...newProps };
}