如何获取global.window.localstorage Inside getServersideProps

发布于 2025-01-22 07:44:45 字数 878 浏览 2 评论 0原文

我有一些组件,可以通过数据获取道具并渲染数据。在我的getServersideProps函数中,我需要从localstorage获得数据,但是由于window is undefined 。

我尝试使用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}
  };
}

我也尝试使用使用效果,但出错

React Hook“ useffect”在函数“ getServersideprops”中称为 既不是React功能组件,也不是自定义React Hook 功能。

I have some component which get props with data and render it data. In my getServerSideProps function I need to get data from localStorage, but I can't do it because of window is undefined.

I tried using if (typeof window !== 'undefined') but it's still not working. What's wrong with my code?

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}
  };
}

I'm also tried use useEffect, but got error

React Hook "useEffect" is called in function "getServerSideProps" that
is neither a React function component nor a custom React Hook
function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请帮我爱他 2025-01-29 07:44:45

参考 documentation

如果您从页面中导出一个称为getServersideProps(服务器端渲染)的函数,则Next.js将使用getserverversideprops 。


localStorage仅在客户端上可用,并且您正在尝试仅在服务器端函数中访问它,您可以使用诸如

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

请访问

另一种方法是使用 dynamigic import 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

Referring to the documentation

If you export a function called getServerSideProps (Server-Side Rendering) from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps.

Localstorage is only available on the client side and you are trying to access it in a server side only function , you can use something like

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

Please review this article to get more information on running client side only code.

Another approach would be to use a dynamic import where the hello3 component would contain the code accessing local storage.

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
痴情 2025-01-29 07:44:45

getserverserversideprops 仅在服务器端触发,并且在客户端无法使用

getServersideProps仅在服务器端运行,并且永远不会在浏览器上运行。

如果您想拥有该存储逻辑,我建议您改用cookie。不像LocalStorage,服务器端和客户端都可以使用Cookie。

来修改逻辑

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}
  };
}

您可以使用cookie的另一种可能的方法 ,是使用 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;
}

getServerSideProps only trigger on the server-side and it won't be available on the client-side

getServerSideProps only runs on server-side and never runs on the browser.

If you want to have that storage logic, I'd suggest you use cookies instead. Not like localStorage, cookies are available on both server-side and client-side.

You can modify your logic like below with 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}
  };
}

Another possible approach is using getInitialProps which is available on both sides

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文