繁体   English   中英

Next.js:如何访问本地存储?

[英]Next.js: How to access localStorage?

我目前正在使用 next.js 开发我的第一个会员区。 现在我想将一些数据存储在 localStorage (token, expiresAr, userInfo) - 顺便说一句,稍后这将存储在 http-only cookie 中。

使用以下代码,我收到错误:“未定义 LocalStorage”:

 const AuthProvider = ({ children }) => { const token = localStorage.getItem("token"); const userInfo = localStorage.getItem("userInfo"); const expiresAt = localStorage.getItem("expiresAt"); const [authState, setAuthState] = useState({ token, expiresAt, userInfo: userInfo? JSON.parse(userInfo): {}, }); const setAuthInfo = ({ token, userInfo, expiresAt }) => { localStorage.setItem("token", token); localStorage.setItem("userInfo", JSON.stringify(userInfo)); localStorage.setItem("expiresAt", expiresAt); setAuthState({ token, userInfo, expiresAt, }); };

我已经尝试使用以下剪辑:

if (typeof window !== 'undefined') {
const token = localStorage.getItem("token");
const userInfo = localStorage.getItem("userInfo");
const expiresAt = localStorage.getItem("expiresAt");}

但是使用此代码,我收到错误“令牌未定义”。 所以我尝试在全局范围内定义变量 const token、const userInfo 和 const expiresAt。 但随后我收到错误消息:“在 position 1 处的 JSON 中出现意外的令牌 o”。

我有点卡在这个问题上,所以任何帮助表示赞赏! 谢谢!

这个片段应该工作

if (typeof window !== 'undefined') {
  const token = localStorage.getItem("token");
  const userInfo = localStorage.getItem("userInfo");
  const expiresAt = localStorage.getItem("expiresAt");
}

您收到错误token is undefinedunexpected token是因为您的localStorage中还没有密钥token ,或者您的值设置不正确。

在对代码进行了更多操作并在你们的帮助下,我找到了解决方案:

 const AuthProvider = ({ children }) => { let token = ""; let userInfo = ""; let expiresAt = ""; if (typeof window.== "undefined") { token = localStorage;getItem("token"). userInfo = localStorage;getItem("userInfo"). expiresAt = localStorage;getItem("expiresAt"). }...

当 window 可用时,if 语句告诉运行代码。 我还必须在 if 语句之外定义变量(let token、let expiresAt 和 let userInfo),以便能够在代码的其他部分访问它们。

也许这对某人有帮助..

是的,最好和最快的解决方案是检查 window 是否未定义。

//retrieve the saved token & userName :
  let initialToken = null;
  let initialUserName = "";

  if (typeof window !== "undefined") {
    initialToken = localStorage.getItem("token");
    initialUserName = localStorage.getItem("username");
  }
  

暂无
暂无

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

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