Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

javascript - 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>

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 });
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...