如何在页面重新加载时清除 react-router 中的 location.state? [英] How do I clear location.state in react-router on page reload?
问题描述
我目前正在通过我的状态更改路线,如下所示:
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屋!