如果刷新,如何保留 props.location.state 值
How to retain props.location.state value if I refreshed
第一次进入包含 this.props.location.state
的页面时,会获取所有状态详细信息,但刷新该页面时,我们只会获取未定义的状态。如何在刷新时保留 props.location.state
的值。
道具控制台刷新如下
logged props: undefined
我认为你正在使用 HashRouter
使用 browserRouter
然后数据将被保留。
您可以在 componentDidMount()
中编写一个 if-else 块,它首先检查 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.
}
第一次进入包含 this.props.location.state
的页面时,会获取所有状态详细信息,但刷新该页面时,我们只会获取未定义的状态。如何在刷新时保留 props.location.state
的值。
道具控制台刷新如下
logged props: undefined
我认为你正在使用 HashRouter
使用 browserRouter
然后数据将被保留。
您可以在 componentDidMount()
中编写一个 if-else 块,它首先检查 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.
}