localStorage未在next js中定义

py49o6xq  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(164)

我正在使用下一个。js前端我想从localStorage中获取用户,但作为下一个。js是服务器端渲染,我无法获取localStorage。我应该怎么做才能获得localStorage?

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import authService from "./authService";

const getUserfromLocalStorage = localStorage.getItem("user")
  ? JSON.parse(localStorage.getItem("user"))
  : null;

const initialState = {
  user: getUserfromLocalStorage,
  isError: false,
  isLoading: false,
  isSuccess: false,
  message: "",
};

export const login = createAsyncThunk('auth/login', async (user, thunkAPI) => {
  try {
    return await authService.login(user);
  } catch (error) {
    return thunkAPI.rejectWithValue(error);
  }
});

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(login.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.isLoading = true;
        state.isSuccess = false;
        state.user = action.payload;
      })
      .addCase(login.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.isSuccess = false;
        state.user = null;
      });
  },
});

export default authSlice.reducer;

djmepvbi

djmepvbi1#

这是因为您正在尝试访问客户端变量-窗口。localStorage在不存在window的服务器上。

const getUserfromLocalStorage = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;

这里首先要检查是否定义了window

if (typeof window !== 'undefined') {
  const getUserfromLocalStorage = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;
}

或者您可以检查是否使用可选链接定义了窗口

const getUserfromLocalStorage = window?.localStorage?.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;

这里更像“React”的解决方案是使用像useEffect这样的钩子来执行这个动作。

import { useEffect } from "react";

useEffect(() => {
  const getUserfromLocalStorage = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;
}, []);

相关问题