reactjs - 如何使用状态更新创建事件(通过 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
;我的假设是否正确?
解决方案
getDerviedStateFromProps
是一个静态函数,所以你不能this
从它访问,静态函数绑定到类本身而不是组件的实例。我相信它故意这样做是为了避免副作用。
因此,this.history.push
您应该使用nextProps.history.push
在生命周期挂钩参数中获得的而不是使用。
但是对于您的用例,因为您说您实际上并不需要返回状态,这意味着您实际上并不需要派生状态,因为您不会根据特定道具更改内部状态。您应该componentDidUpdate
改为使用副作用,请参阅https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops
推荐阅读
- batch-file - 在命令行中运行命令有效,在 bat 中无效
- java - SSL 加密:RSA Premaster 密码错误
- javascript - Javascript If false return behaving in unexpected way. Why?
- docker - Hyperledger Docker Container Dependency
- influxdb - InfluxDB 将不同的字段值合并到单个打印输出
- php - Best way to prevent simultaneous login
- angular - 使用 angularfire2 从存储中下载列表
- python - Error with python packages
- rust - Get value out of optional HashMap only when present
- python - EBNF Nested Optional/Grouping