【问题标题】:Persist state after reload in react重新加载后保持状态反应
【发布时间】:2021-06-02 10:49:30
【问题描述】:

一旦我通过向该页面传递道具进入特定页面,我希望能够重新加载页面而不会丢失状态,目前,当我重新加载时,页面会抛出一个错误,即缺少道具。 例如,如果我使用

history.push({ pathname: '/animal-details',animal_id: animal.id }) 它在这些下一页上显示了详细信息,但是当我重新加载页面时,数据消失并且页面留空。如何解决这个问题? 谢谢。

【问题讨论】:

  • history.push(`history.push 这看起来像是错字?
  • 谢谢我编辑了它。
  • 在页面重新加载之间保持状态通常是通过 cookie 和本地/会话存储来完成的。

标签: javascript reactjs state persistence reload


【解决方案1】:

除了使用 localStorage 或 cookie,我认为将 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 执行类似的操作。

【讨论】:

    【解决方案2】:

    你可以使用:

    1. 本地存储
    localStorage.getItem('yourData');
    

    1. Cookie

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

    【讨论】:

      猜你喜欢
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-23
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多