[英]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.