如何在 getServerSideProps 中获取本地存储数据

Kus*_*ish 5 reactjs next.js

我正在使用 NextJS 12。我正在尝试获取本地存储对象。当我在内部使用 localstorage 时,getServerSideProps出现这样的错误ReferenceError: localStorage is not defined。我也尝试在函数之外使用它,但仍然收到此错误。有什么办法可以在里面使用吗getServerSideProps

export async function getServerSideProps({ query }) {
    const id = query.id;
    const getData = JSON.parse(localStorage.getItem("form"));
    console.log(getData)
  
    return {
      props: {},
}
Run Code Online (Sandbox Code Playgroud)

Ram*_*kay 5

欢迎使用 StackOverflow,如文档中所述

如果您从页面导出一个名为getServerSideProps (服务器端渲染)的函数,Next.js 将使用 getServerSideProps 返回的数据在每个请求上预渲染此页面。

Localstorage 仅在客户端可用,并且您尝试在仅服务器端功能中访问它,您可以使用类似

if (typeof window !== 'undefined') {
// your code 
  const id = query.id;
    const getData = JSON.parse(localStorage.getItem("form"));
    console.log(getData)
  
}
Run Code Online (Sandbox Code Playgroud)

请查看本文以获取有关仅运行客户端代码的更多信息。

另一种方法是使用动态导入,其中 hello3 组件将包含访问本地存储的代码。

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/hello3'),
  { ssr: false }
)

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  )
}

export default Home
Run Code Online (Sandbox Code Playgroud)


小智 5

另一种方法是使用 cookie 而不是使用localstorage,当我开发上一个应用程序时我遇到了同样的问题,我使用nookies包解决了它

Nookies:Next.js 的 cookie 助手集合