错误:服务器错误ReferenceError: localStorage未定义在生成页面时发生此错误。所有控制台日志将显示在终端窗口中。
import { LOGIN_SUCCESS, LOGIN_FAIL, LOGOUT } from "../actions/types";
const user = JSON.parse(localStorage.getItem("user"));
const initialState = user
? { isLoggedIn: true, user }
: { isLoggedIn: false, user: null };
export default function (state = initialState, action) {
const { type, payload } = action;
switch (type) {
case LOGIN_SUCCESS:
return {
...state,
isLoggedIn: true,
user: payload.user,
};
case LOGIN_FAIL:
return {
...state,
isLoggedIn: false,
user: null,
};
case LOGOUT:
return {
...state,
isLoggedIn: false,
user: null,
};
default:
return state;
}
}
这与服务器端呈现和客户端呈现有关。由于Next.js提供了SSR,因此需要考虑使用window、localStorage等对象。在编译客户端时,这些对象都很好,但是当Nextjs编译服务器端时,它会显示像你分享的错误。
你可以这样写:
let user = null;
if (typeof window !== "undefined") {
user = JSON.parse(localStorage.getItem("user"));
} else {
// ... server-side logic
}
其他解决方案参见:https://dev.to/vvo/how-to-solve-window-is-not-defined-errors-in-react-and-next-js-5f97