React刷新重定向到主页,其url和刷新页面的url相同



我有react router dom来从一个组件路由到另一个组件。请提及下面用于组件之间路由的代码。

<Router>
<Switch>
<Route path="/" component={Language} exact />
<Route path="/termsandconditions" component={TermsConditions} exact />
</Switch>
</Router>

实际问题是,当我在url/termsandconditions中时,我刷新了页面,它将重定向到Language组件,url为/termsandconditions。如果url在/termsandconditions中,

TermsConditions组件刷新页面时的任何解决方案。它将保留在当前URL的组件中。

我认为您可以使用会话存储来保存页面刷新事件之前的最后一条路由

window.onbeforeunload = () => {
window.sessionStorage.setItem('lastRoute', JSON.stringify(window.location.pathname))
}

将上面的代码添加到你的App.js useEffect中,然后你就可以访问会话存储,获取最后一条路由并重定向到它。

最新更新