关于react.js:React新生命周期getDerivedStateFromProps的理解与使用

0次阅读

共计 1690 个字符,预计需要花费 5 分钟才能阅读完成。

在我的项目过程中遇到了同一文件门路不同参数,路由跳转后并未调用 componentWillDidMount,因而用到了 React 新生命周期:static getDerivedStateFromProps(nextProps, preState)并在此记录!

getDerivedStateFromProps 的呈现:

componentWillReceiveProps 在 React 新的生命周期中被勾销,这个生命周期函数是为了代替 componentWillReceiveProps,所以在 须要应用 componentWillReceiveProps 的时候 ,就能够思考 应用 getDerivedStateFromProps 来进行代替 了。

getDerivedStateFromProps 的性能:

我的了解:getDerivedStateFromProps 这个办法名曾经十分语义话了,简略翻译过去就是从 Props 中取得 State,所以该函数的性能就是 从更新后的 props 中获取 State,它让组件在 props 产生扭转时更新它本身的外部 state

getDerivedStateFromProps 的参数:

nextProps:与 componentWillReceiveProps 的 nextProps 参数雷同。
preState:原数据 state 中各数据的值。

getDerivedStateFromProps 的触发条件:

会在调用 render 办法之前调用,即 在渲染 DOM 元素之前会调用,并且在初始挂载及后续更新时都会被调用
联合下图 新 React 生命周期 了解起来会简略一些:

getDerivedStateFromProps 的应用:

1. 当 props 数据某个值发生变化时对 state 进行赋值:

static getDerivedStateFromProps(nextProps, preState) {const {match: {params: {instrumentId}}} = nextProps;
    // 此处当传入的 instrumentId 发生变化的时候,更新 state
    if (instrumentId !== preState.instrumentId) {
        return {instrumentId: instrumentId,};
    }
    return null;    // 不变动,则对于 state 不进行任何操作
}

2. 无条件的依据 prop 来更新外部 state,也就是只有有传入 prop 值,就更新 state
(然而如果只有 props 值扭转,就更新 state,其实间接用 props 的值去进行操作就能够了。)

static getDerivedStateFromProps (props, state) {const {match: {params: {instrumentId}}} = nextProps;
    return {instrumentId: instrumentId,}
}

3. 因为 getDerivedStateFromProps 被定义为静态方法,所以 不能够间接应用 this.×××,因而咱们须要 对类进行实例化,才应用类中定义的办法:

class InstrumentCommand extends PureComponent {
                    ......
    static getDerivedStateFromProps(nextProps, preState) {const {match: {params: {instrumentId}}} = nextProps;
        if (instrumentId !== preState.instrumentId) {new InstrumentCommand(nextProps).implementDispatch(instrumentId)
        }
    }
}
                    ......

getDerivedStateFromProps 的注意事项:

1.getDerivedStateFromProps 办法 肯定要 return 一个值 ,如果不须要对 state 操作,只需return null;即可,不可返回 undefined。
当 getDerivedStateFromProps()没有明确返回任何内容时,控制台会输入正告:

正文完
 0