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