我正在使用下一个。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;
1条答案
按热度按时间djmepvbi1#
这是因为您正在尝试访问客户端变量-窗口。localStorage在不存在window的服务器上。
这里首先要检查是否定义了window。
或者您可以检查是否使用可选链接定义了窗口
这里更像“React”的解决方案是使用像useEffect这样的钩子来执行这个动作。