Reactjs 在react js中的getDerivedStateFromProps更改状态后调用方法
我有一个react组件,在getDerivedStateFromProps中的状态更改之后,我需要在其中调用一个方法。 假设我有一个方法foo,在getDerivedStateFromProps中的状态更改后调用Reactjs 在react js中的getDerivedStateFromProps更改状态后调用方法,reactjs,Reactjs,我有一个react组件,在getDerivedStateFromProps中的状态更改之后,我需要在其中调用一个方法。 假设我有一个方法foo,在getDerivedStateFromProps中的状态更改后调用 //state state: { "a": "", "b": "" } static getDerivedStateFromProps(nextProps, currentState){ if(nextProps.show){ // nextP
//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生命周期挂钩的信息