【问题标题】:Next.js getStaticProps localstorage is not definedNext.js getStaticProps localstorage 未定义
【发布时间】:2021-10-17 23:38:35
【问题描述】:

我的用户 ID 存储在本地存储中,我想在 getStaticProps 中访问它以获取当前用户的订阅者,但我收到 Local storage is not defined 错误。

请问有什么解决办法吗?

这是我的代码:

export async function getStaticProps() {
  const userData = {
    id: localStorage.getItem("user_id"),
  };
  const subscribersAPi = await fetch(
    `url for server`
  );
  const result = await subscribersAPi.json();
  return {
    props: { data: result },
  };
}

【问题讨论】:

  • window.localStorage 是仅在浏览器上可用的 Web API。 getStaticProps 在 Node.js 环境中的服务器上(和构建时)运行,并且无权访问 localStorage
  • @juliomalves 有什么方法可以传递用户 ID 吗?
  • 无法使用getStaticProps 传递特定于用户的数据。您可以考虑使用getServerSidePropsuse cookies 来传递数据,而不是使用localStorage
  • @juliomalves 好的,非常感谢

标签: reactjs next.js


【解决方案1】:

localStoragesessionStorage 是 Browser 为我们提供的 Window Object 方法之一。 Learn more!

服务器在 SSR 中渲染应用时,将没有浏览器,因此不存在 window,因此您无法访问本地存储。
相反,您应该使用useEffectwindow 中访问它们

const MyComponent = () => {
  const [data, setData] = useState("");

  useEffect(() => {
    setData(localStorage.getItem("myData"));
  }, []);

  return <div>{data}</div>;
};

【讨论】:

  • 但是如果我需要我的 userId 从服务器获取数据怎么办?无论如何我可以将参数传递给我的 getStaticProps 吗?
  • 使用 SSR,可以,但不推荐。因此,SSR 对于我们有动态路由的应用程序没有用。您可以使用getStaticPaths,它的工作方式类似于 getStaticProps,但请求受到限制,因为每次构建它都会调用 API,并且 API 会限制连续请求
  • 这里是getStaticPropsnextjs.org/docs/basic-features/…的文档
猜你喜欢
  • 2021-03-18
  • 2022-10-31
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
相关资源
最近更新 更多