How do I clear location.state in react-router on page reload?

前端 未结 4 1856
余生分开走
余生分开走 2021-01-03 23:01

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



        
相关标签:
4条回答
  • 2021-01-03 23:10

    After you used the state, dispatch an action with an empty state again to clean the state.

    this.props.dispatch(replace({
      ...this.props.location,
      state: undefined
    });
    
    0 讨论(0)
  • 2021-01-03 23:15

    I would suggest not to use the location prop here, but to create a Route (wherever you define them) with a path: /transactions/:transactionId, and to catch the transactionId in the prop props.match.params.transactionId inside of the target component. Then in the componentDidMount you can dispatch the API request action in order to fetch the transaction. Don't forget to delete the state param from the props of the Link.

    0 讨论(0)
  • 2021-01-03 23:18

    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 });
        }
    }
    
    0 讨论(0)
  • 2021-01-03 23:18

    There is better approach without using the 3 party library.

    We can use history.replace()

    https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/history.md

    componentDidMount(){
     const {location,history} = this.props;
     //use the state via location.state
     //and replace the state via
     history.replace() 
    }
    
    0 讨论(0)
提交回复
热议问题