如何使用状态更新创建事件(通过getDerivedStateFromProps)

时间:2019-05-17 12:50:09

标签: reactjs redux react-component

我正在尝试将componentWillReceiveProps方法更改为静态getDerivedStateFromProps,但不知道如何在getDerivedStateFromProps函数中使用关键字this。

最初,我想在this.props.history.push()内使用getDerivedStateFromProps,但不知道怎么做。
然后,我尝试返回状态(应该按照getDerivedStateFromProps进行操作),并且无法使用它创建事件。简短地看一下代码会使我的问题更容易理解。

 static getDerivedStateFromProps(nextProps, prevState){
   if(nextProps.passwordResetResult.message==="Password reset 
      Successfully")
    {
      alert("Password reset successfully please login again");
         this.props.history.push('/home')
    }
   }

我知道我应该在最后返回状态;但是我没有发现它对我有帮助,因为我不了解如何创建一个事件,该事件将在返回后在状态更改时触发,然后触发this.props.history.push()

以上代码导致错误

  

this.props未定义。

我知道我不能在this内使用getDerivedStateFromProps关键字;我认为正确吗?

1 个答案:

答案 0 :(得分:1)

getDerviedStateFromProps是静态函数,因此您无法从中访问this,静态函数绑定到类本身而不是组件实例。我相信它有意这样做是为了避免副作用。

因此,应该使用生命周期挂钩参数中的this.history.push来代替nextProps.history.push

但是对于您的用例,因为您说过您并不需要真正返回状态,这意味着您实际上并不需要派生状态,因为您无需根据特定的道具更改内部状态。对于副作用,应使用componentDidUpdate代替,请参见https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops