在React中调用getDerivedStateFromProps中的方法

时间:2018-04-05 05:38:20

标签: reactjs react-native

在升级对版本16.3的反应之前,我会根据这样的道具变化调用一个方法:

componentWillReceiveProps(nextProps){
   if(this.props.country.length !== nextProps.country){
    doSomething(); //example calling redux action
    }
}

componentWillReceiveProps对版本16.3不安全,我们必须使用getDerivedStateFromProps。但是,此方法返回一个对象,我不知道如何从内部调用方法,就像我使用componentWillReceiveProps

一样

3 个答案:

答案 0 :(得分:14)

是的,您需要返回一个对象,这是从nextProp派生的新状态。根据文件:

  

getDerivedStateFromProps应该返回一个更新状态的对象,或者为null以指示新的props不需要任何状态更新。

,因为您未在componentWillReceiveProps内以任何方式更新状态,因此您应使用componentDidUpdate代替getDerivedStateFromProps

componentDidUpdate(prevProps){
  if ( prevProps.country !== this.props.country.length ) {
    doSomething(); //example calling redux action
  }
}

答案 1 :(得分:4)

对于这种情况,OP使用componentDidUpdate是好的,但我发现自己需要getDerivedStateFromProps所以我必须将我的自定义函数设置为静态并使用类中的名称来调用它getDerivedStateFromProps。像这样:

componentDidMount() {
    const something = ClassComponentName.runThisFunction();
    this.setState({ updatedSomething: something });
}

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.key !== prevState.key) {
        return { 
            updatedSomething: ClassComponentName.runThisFunction()
        };
    }
    return null;
}

static runThisFunction() {
    //do stuff and return value
}

为了澄清,这是在加载时以及新道具到达时更新组件的状态。这绝对让我回到了我的打字时代。希望它有所帮助!

答案 2 :(得分:0)

如果需要在“ getDerivedStateFromProps”中调用函数,可以将该函数置于构造函数中的状态,然后从状态中在“ getDerivedStateFromProps”中获取此函数。

将函数置于构造函数中的状态:

constructor(props){
   super(props);
   this.state = {
      func1:this.func1.bind(this)
   }
}

从getDerivedStateFromProps中的状态获取函数:

getDerivedStateFromProps(props,state){
   return {
       model:state.func1(props.model)
   }
}
相关问题