reactjs - Gatsby:使用localStorage存储数据

标签 reactjs cookies local-storage gatsby server-side-rendering

我有一个 Gatsby 网站,并且正在实现 GDPR 同意横幅。我想将状态存储在本地存储中,其中包含与用户是否接受 GDPR 条款相关的“true”或“false”字符串。

例如,用户首次访问该网站。在本地存储中,有一个“GDPR_Accepted”键设置为“false”。如果用户不接受主页上的 GDPR 条款,则横幅将继续显示在用户访问的每个页面上。当用户单击接受时,GDPR_Accepted 值设置为“true”,并且我的 React 组件中的三元运算符应用隐藏横幅的 CSS 类。

因为我使用本地存储,即使用户离开页面并稍后返回(假设他们没有清除浏览历史记录),“true”值也应该保留。问题出在 Gatsby 身上。 Gatsby 使用服务器端渲染,当用户接受 GDPR 条款并离开网站并返回时,GDPR 值将重置为“false”。当设置为“true”时,Gatsby 无法保留之前的本地存储数据。

如何在 Gatsby 项目中将数据保存在本地存储中?仅使用 React 状态来存储用户是否接受 GDPR 条款是否更有意义?

最佳答案

我构建了一个完整的工作示例只是为了确认它是否有效。只需运行 gatsby build然后gatsby serve看看它构建后应该如何运行。

/* src/pages/index.js */

import React, {useState, useEffect} from 'react'

const IndexPage = () => {
  const [agreed, setAgreed] = useState(false)

  // This runs when the page is loaded.
  useEffect(() => {
    if (localStorage.getItem('agree')) {
      setAgreed(true)
    }
  }, [])

  const handleClick = () => {
    localStorage.setItem('agree', 'true')
    setAgreed(true)
  }

  const AgreeButton = <button onClick={handleClick}>Click me to agree</button>

  return (
    <>
      <h1>Welcome to my page!</h1>
      {agreed
        ? <p>You agreed!</p>
        : AgreeButton
      }
    </>
  )
}

export default IndexPage

我想你可能误解了 Gatsby 的工作原理。通过像 Create React App 这样的东西,服务器会发送一个非常简单的 HTML 文档,其中包含一个 <root>体内的元素。对于 Gatsby,页面是在构建时构建的。这对性能有很大帮助,因为用户的浏览器不必完全从头开始构建页面。

也许您认为,正因为如此,您无法使用 Create React App 做很多事情,因为它在到达用户之前将所有内容都归结为 HTML。事实并非如此。多亏了 React Hydration,你仍然可以使用钩子(Hook)和状态以及所有有趣的东西。来自 Gatsby docs :

the browser can “pick up” where the server left off with the contents created by Gatsby in the /public folder and render the site in the browser like any other React app would.

关于reactjs - Gatsby:使用localStorage存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65496028/

相关文章:

javascript - 仅 http 的 cookie 安全吗?

mysql - 如何为所有浏览器存储无限量的 cookie 条目

asp.net - IdentityServer4 中的 Cookie

javascript - 对象属性在 console.log 中显示为未定义

ios - 如何在 Objective C 中打开本地保存的 PDF 文件

javascript - 使用重复的 div React.JS 切换事件的 CSS 状态

javascript - 在 React 组件中,foo(){} 和 bar = () => {} 有什么区别,什么时候应该使用哪个?

reactjs - SSR 中请求的路由的双脚本标签

javascript - 如何在return()中调用var

javascript - 使用 ContentEditable 复制和粘贴表格