首页 > 解决方案 > react js中通过getDerivedStateFromProps调用状态变化后的方法

问题描述

我有一个反应组件,我需要在 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")
}

标签: reactjs

解决方案


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

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

这意味着props.foo将在 props.show 更改并且 props.show 为 true 时调用


推荐阅读