Next.js:如何访问localStorage?

Ewa*_*_Du 5 javascript authentication local-storage next.js

我目前正在使用 next.js 开发我的第一个会员区。现在我想在 localStorage 中存储一些数据(token、expiresAr、userInfo) - 顺便说一句,稍后这些数据将存储在仅 http 的 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,
    });
  };
Run Code Online (Sandbox Code Playgroud)

我已经尝试使用以下片段:

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

但使用此代码时,我收到错误“令牌未定义”。所以我尝试全局定义变量 const token、const userInfo 和 const expiresAt。但随后我收到错误:“JSON 中位置 1 处出现意外的标记 o”。

我对这个问题有点困惑,所以非常感谢您的帮助!谢谢!

bur*_*alc 2

这段代码应该可以工作

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

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