Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在react js中的getDerivedStateFromProps更改状态后调用方法_Reactjs - Fatal编程技术网

Reactjs 在react js中的getDerivedStateFromProps更改状态后调用方法

Reactjs 在react js中的getDerivedStateFromProps更改状态后调用方法,reactjs,Reactjs,我有一个react组件,在getDerivedStateFromProps中的状态更改之后,我需要在其中调用一个方法。 假设我有一个方法foo,在getDerivedStateFromProps中的状态更改后调用 //state state: { "a": "", "b": "" } static getDerivedStateFromProps(nextProps, currentState){ if(nextProps.show){ // nextP

我有一个react组件,在getDerivedStateFromProps中的状态更改之后,我需要在其中调用一个方法。 假设我有一个方法foo,在getDerivedStateFromProps中的状态更改后调用

//state
state: {
    "a": "",
    "b": ""
}

static getDerivedStateFromProps(nextProps, currentState){
    if(nextProps.show){
        // nextProps.foo() function to be called after the state changes to "a": "Apple","b": "Ball"
        return {
            "a": "Apple",
            "b": "Ball"
        }
    }
}
//The function in parent component
foo = () => {
    console.log("Function called")
}

调用
props.foo()
取决于
props.show,
,因此您可以使用
componentdiddupdate
生命周期方法

componentDidUpdate(prevProps) {
    if (this.props.show !== prevProps.show && this.props.show) {
      this.props.foo();
    }
  }

这意味着当props.show发生更改并且props.show为true时,将调用
props.foo
。我不确定您究竟为什么要使用getDerivedStateFromProps生命周期挂钩。
我相信您已经意识到,派生状态会导致冗长的代码,并使您的组件难以思考。

另一方面,如果您唯一的要求是在某些道具更新或本地状态更新时运行父函数,那么您可能希望尝试使用生命周期挂钩,componentdiddupdate

看一下代码片段

componentDidUpdate(prevProps, prevState) {
    //check for update in props
    if(prevProps.show !== this.props.show){
        //call the parent function
        this.props. foo()
    }
}
如果必须使用getDerivedStateFromProps,可以这样想,因为生命周期方法本质上返回一个对象,该对象将更新状态对象。您可以使用componentDidUpdate来侦听状态更改并调用父属性函数

componentDidUpdate(prevProps, prevState){
    //check for update in state after derived state
    if( (prevState.a !== this.state.a) || (prevState.b !== this.state.b) ){
        //call the parent function
        this.props.foo()
    }
}
在任何情况下,您都应该通过单击从官方文档中阅读更多关于getDerivedStateFromProps生命周期挂钩的信息