如何在重新加载页面时清除react-router中的location.state? [英] How do I clear location.state in react-router on page reload?

查看:138
本文介绍了如何在重新加载页面时清除react-router中的location.state?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在通过以下路线更改通知我的状态:

I am currently passing my state on route change like below:

<Link to={{
           pathname:`/transactions/${props.transaction.id}`,
           state: {transaction: props.transaction}
         }}> View Details </Link>

我的逻辑是,如果存在"location.state.transaction",请不要获取新数据,否则请获取数据.

My logic is that if "location.state.transaction" exists, don't fetch new data, else, fetch data.

现在的缺陷是重新加载页面时.如果用户重新加载页面,则应用程序需要获取新数据.我以为如果重新加载,"location.state"将被清除,但状态显然保存在sessionStorage中.

Now the flaw is when there is a page reload. The application needs to fetch new data if the user reloads the page. I thought "location.state" would get cleared if there is a reload, but apparently the state is saved in sessionStorage.

我该如何解决?我每次都只能获取新数据,但是当单击查看详细信息"链接时,它不应获取数据.

How do I work around this? I could just fetch new data every time, but it should not fetch data when the 'View Details' Link is clicked.

推荐答案

我也遇到了这个问题,最终我要做的是从React Router检索浏览器历史记录并清除特定的location.state属性.因此,在您的情况下,将是 transaction .我是在 componentDidMount 中执行此操作的,这样,当您第一次访问该页面后,该属性将不再存在,

I also ran into this problem, and what I ended up doing was retrieving the browser history from react router and clearing specific location.state properties. So in your case, it would be transaction. I did this in componentDidMount so that after the first time you go to the page, that property should no longer be there,

import createHistory from 'history/createBrowserHistory'

...

componentDidMount(){
    const history = createHistory();
    if (history.location.state && history.location.state.transaction) {
        let state = { ...history.location.state };
        delete state.transaction;
        history.replace({ ...history.location, state });
    }
}

这篇关于如何在重新加载页面时清除react-router中的location.state?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆