componentWillReceiveProps、getDerivedStateFromProps替换方案

2,180 阅读1分钟

react 16.9.0以后,componentWillReceiveProps被废除,使用componentWillReceiveProps编译就会报错,这时候最简单的方法是用UNSAFE_componentWillReceiveProps代替。但是既然人家名字都叫unsafe,那么肯定是不推荐使用的。官方推荐getDerivedStateFromProps来替换componentWillReceiveProps。下面就来说说替换方法。

  • 原来的写法:
componentWillReceiveProps(nextProps, prevState){
    const { changeTab } = nextProps;
    if (changeTab !== prevState.changeTab) {    //判断props传入的值是否发生变化
        //执行操作,可以setState也可以调组件里面的方法
    }
}
  • 编译器推荐的用法

image.png

UNSAFE_componentWillReceiveProps(nextProps, prevState) {
    const { changeTab } = nextProps;
    if (changeTab !== prevState.changeTab) {    //判断props传入的值是否发生变化
        //执行操作,可以setState也可以调组件里面的方法
    }
}
  • getDerivedStateFromProps替换方案
static getDerivedStateFromProps(nextProps, prevState) {
    const { changeTab } = nextProps;
    if (changeTab !== prevState.changeTab) {
        return {
            changeTab
        };
    }
    return null;
}

注意:**getDerivedStateFromProps是静态函数,不能用this调到组件里面的方法!**如果需要调到组件里面的方法,可以结合componentDidUpdate使用。

componentDidUpdate(prevProps, preState) {
    //判断该state是否改变
    if (this.state.changeTab !== preState.changeTab) {
        //这里来调组件的方法
    }
}

用getDerivedStateFromProps和componentDidUpdate就可以替换componentWillReceiveProps啦