简体   繁体   中英

how to maintain history state by using react-router-dom among components?

I have a use case in which i use useHistory hook to redirect and pass state between components.

/* first component */

const {useHistory} from 'react-router-dom';
const history = useHistory();
history.push({pathname: '/next',course: 'some value'});

/* second component */

const location = useLocation();
const value = location.course; /* return 'some value' */
history.push('/nextroute') /* redirects to the third component */

Now the problem occurs when i press go back button from the browser, the location state gets undefined. Now i have views in which i have to use 'history' to redirect and pass state to components. how can i maintain that state when i press the back button on the browser or when ever a page refresh happens. Also what other effect way is there to pass state for this specific use case.

If I understand correctly I think you are getting undefined because react router is overriding your course value.

Push your course value to the location.state instead of the location itself eg:

history.push({
  pathname: '/next',
  state: {
    course: 'some value'
  }
});

then you can access it in your next component with history.location.state.course;

You may be getting undefined because your are trying to go back to the first form and haven't yet set a state for that route yet. You will first need to replace the state and then push to the new form like so:

// replace the current routes state
history.replace({
  pathname: "/",
  state: {
    courses: 'your stuff'
  }
});

//then push this state to your next route for use there
history.push({
  pathname: "/next",
  state: {
    courses: 'your stuff'
  }
});

Here is a simple example Codesandbox Example .

Note: if you want a state object that will be specific to each route then use the location state to store your data. If you have general state that will change and is not bound to a specific route I would use React Context instead.

Here is an example of that in action CodeSandbox With Context Example

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM