繁体   English   中英

如何在 getServerSideProps 中获取 global.window.localStorage

[英]How to get global.window.localStorage inside getServerSideProps

我有一些组件可以获取带有数据的道具并渲染它的数据。 在我的getServerSideProps function 中,我需要从localStorage获取数据,但我不能这样做,因为windowundefined

我尝试使用if (typeof window !== 'undefined')但它仍然无法正常工作。 我的代码有什么问题?

const MainComponent = ({serverResponseData}) => {
  // ... some code
  console.log(serverResponseData))
  // ... some code
}

export async function getServerSideProps() {
  let filterId = []

  if (typeof window !== 'undefined') {
    filterId = global.window?.localStorage.getItem('filterId') || '';
  }

  // ...some code, and filterId variable still empty array
  const scoresRes = await fetchData('scores',{filterId});

  return {
    props: {scoresRes}
  };
}

我也尝试过使用 useEffect,但出现错误

React Hook“useEffect”在 function“getServerSideProps”中被调用,它既不是 React function 组件,也不是自定义 React Hook function。

参考文档

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

Localstorage 仅在客户端可用,而您正试图在服务器端仅访问它 function,您可以使用类似

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

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

另一种方法是使用动态导入,其中 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

getServerSideProps只在服务端触发,客户端不可用

getServerSideProps 仅在服务器端运行,从不在浏览器上运行。

如果您想拥有该存储逻辑,我建议您改用 cookies。 与 localStorage 不同,cookies 在服务器端和客户端都可用。

您可以使用 cookies 修改您的逻辑,如下所示

export async function getServerSideProps(context) {
  const filterId = context.req.cookies.filterId || ''; //get filterId from cookies

  // ...some code, and filterId variable still empty array
  const scoresRes = await fetchData('scores',{filterId});

  return {
    props: {scoresRes}
  };
}

另一种可能的方法是使用双方都可用的getInitialProps

MainComponent.getInitialProps() {
  let filterId = []

  if (typeof window !== 'undefined') {
    filterId = global.window?.localStorage.getItem('filterId') || '';
  }

  // ...some code, and filterId variable still empty array
  const scoresRes = await fetchData('scores',{filterId});

  return scoresRes;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM