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

在我的项目过程中遇到了同一文件门路不同参数,路由跳转后并未调用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()没有明确返回任何内容时,控制台会输入正告:

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理