reactjs - 如果我刷新,如何保留 props.location.state 值
问题描述
当第一次进入页面this.props.location.state
时,会获取所有状态详细信息,但是当刷新该页面时,我们只会得到未定义的状态。props.location.state
即使刷新如何保留值。
刷新时的道具控制台如下
logged props: undefined
解决方案
您可以编写一个 if-else 块,componentDidMount()
其中首先检查是否this.props.location.state
存在。如果确实如此,则将其保存到 localStorage/sessionStorage 并继续执行您的逻辑。如果没有,则检查 localStorage 的状态,该状态将在第一次加载期间保存。
在你的内部componentDidMount()
:
let routeState
if(this.props.location.state){
localStorage.setItem('routeState', JSON.stringify(this.props.location.state))
routeState = this.props.location.state
} else {
routeState = localStorage.getItem('routeState')
if(routeState) routeState = JSON.parse(routeState)
}
if(routeState){
//use routeState ahead
} else {
//Prompt no data.
}
推荐阅读
- kubernetes - 无法调试 pod Kubernetes
- javascript - 导出通过循环生成的多个 Highcharts 到单个 pdf
- angular - 在哪里使用角度解析?在延迟加载模块的路由中还是在父模块的路由中?
- javascript - Http-post 方法在 Javascript 中不起作用
- python - Queryset v/s List Django
- c# - 在 IEntityTypeConfiguration 中访问 DI 服务
使用 ApplyConfigurationsFromAssembly() 程序集扫描时 - python - 如何使用 boto3 在 aws 中检查 s3 访问密钥是否可以访问特定存储桶
- count - SPARQL 中计数列的总和
- asp.net - 如何防止在移动设备中发出一些 HTTP 请求?
- jquery - 在数据表jquery中重新加载页面后如何保持同一个表?