在ReactJS中的getDerivedStateFromProps中调用方法

MBe*_*mam 13 reactjs react-native

在升级之前16.3根据道具的变化对调用动作的版本作出反应我使用类似这样的代码:

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

但在版本componentWillReceiveProps的反应16.3是不安全的,我们必须使用,getDerivedStateFromProps但它说这个方法必须返回对象,我不知道我怎么可以模拟我以前componentWillReceiveProps做的事情与做16.3

Dan*_*ane 18

是的,您需要返回一个对象,该对象是派​​生自的新状态nextProp.根据文件:

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

但是既然你没有以任何方式更新你的状态componentWillReceiveProps,你应该使用componentDidUpdate而不是getDerivedStateFromProps:

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

  • @Shamseer 使用 componentDidUpdate 进行状态更新和 ajax 调用是很好的。getDerivedStateFromProps 的设计非常简洁、纯粹,并且基本上避免了临时需求。同样,React 工程师的动机是鼓励隔​​离和编写纯函数。参考:https://github.com/reactjs/reactjs.org/issues/721#issuecomment-581479874 (2认同)

Mar*_* P. 7

在这种情况下,使用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
}
Run Code Online (Sandbox Code Playgroud)

为了澄清,这是在加载时以及新道具到达时更新组件的状态。这无疑使我回到了键入语言的时代。希望能帮助到你!


小智 7

如果你需要在“getDerivedStateFromProps”中调用一个函数,你可以把这个函数放在constructor中的state,然后从state中的“getDerivedStateFromProps”中获取这个函数。

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

constructor(props){
   super(props);
   this.state = {
      func1:this.func1.bind(this)
   }
}
Run Code Online (Sandbox Code Playgroud)

从 getDerivedStateFromProps 中的状态获取函数:

getDerivedStateFromProps(props,state){
   return {
       model:state.func1(props.model)
   }
}
Run Code Online (Sandbox Code Playgroud)