[英]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.一旦我通过将道具传递到特定页面 go 到特定页面,我希望能够重新加载页面而不会丢失 state,目前,当我重新加载时,页面会抛出错误,即缺少道具。 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. history.push({ pathname: '/animal-details',animal_id: animal.id })
它在这些下一页上显示详细信息,但是当我重新加载页面时,数据消失并且页面留空。 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.除了使用 localStorage 或 cookies 之外,我认为这是一个很好的情况,只需将animal_id
作为路径的一部分。
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.如果您使用react-router-dom
,您可以使用location
道具或useLocation
挂钩获取动物 ID。
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
.如果您出于某种原因不使用react-router-dom
,您也可以使用 vanilla js window.location.href
执行类似的操作。
You can use:您可以使用:
localStorage.getItem('yourData');
or或者
https://www.npmjs.com/package/react-cookie https://www.npmjs.com/package/react-cookie
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.