简体   繁体   中英

Persist state after reload in react

Once I go to a particular page by passing in props to that page I want to be able to reload the page without losing the state, currently, when I reload, the page throws an error, that the prop is missing. For example if I use

history.push({ pathname: '/animal-details',animal_id: animal.id }) it shows the details on these next page but when I reload the page the data goes away and the page is left blank. How to get around this? Thank You.

Aside from using localStorage or cookies, I think this is a good situation to just make the animal_id part of the path.

Instead of doing

history.push({ pathname: '/animal-details',animal_id: animal.id })

I would do:

history.push(`/animal-details/${animal.id}`)

using a template literal.

If you're using react-router-dom , you can get the animal id using the location prop or the useLocation hook.

const path = props.location.pathname.split('/')
const animalId = path[path.length - 1] // the animal id is the last value in the array

If you aren't using react-router-dom for whatever reason, you can also do something similar using vanilla js window.location.href .

You can use:

  1. localStorage
localStorage.getItem('yourData');

or

  1. Cookies

https://www.npmjs.com/package/react-cookie

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