首页 > 解决方案 > 如果我刷新,如何保留 props.location.state 值

问题描述

当第一次进入页面this.props.location.state时,会获取所有状态详细信息,但是当刷新该页面时,我们只会得到未定义的状态。props.location.state即使刷新如何保留值。
刷新时的道具控制台如下

logged props: undefined

标签: reactjsstatereact-props

解决方案


您可以编写一个 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.
}

推荐阅读