首页 > 解决方案 > 如何使用状态更新创建事件(通过 getDerivedStateFromProps)

问题描述

我正在尝试将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')
    }
   }

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

以上代码导致错误

this.props 未定义。

我知道我不能this在里面使用关键字getDerivedStateFromProps;我的假设是否正确?

标签: reactjsreduxreact-component

解决方案


getDerviedStateFromProps是一个静态函数,所以你不能this从它访问,静态函数绑定到类本身而不是组件的实例。我相信它故意这样做是为了避免副作用。

因此,this.history.push您应该使用nextProps.history.push在生命周期挂钩参数中获得的而不是使用。

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


推荐阅读