[英]I am getting the following error using Next js. I am building an authentication pipeline using axios as the http client
The error: Server Error ReferenceError: localStorage is not defined This error happened while generating the page.错误:Server Error ReferenceError: localStorage is not defined 生成页面时发生此错误。 Any console logs will be displayed in the terminal window.任何控制台日志都将显示在终端窗口中。
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;
}
}
It's related to server side rendering and client side rendering.它与服务器端渲染和客户端渲染有关。 As Next.js provides SSR, you need to consider using objects like window, localStorage and so on.由于 Next.js 提供了 SSR,所以需要考虑使用 window、localStorage 等对象。 While compiling client side, those objects are fine but when Nextjs compiles server side, it shows error like you shared.在编译客户端时,这些对象很好,但是当 Nextjs 编译服务器端时,它会显示您共享的错误。
You can use something like this:你可以使用这样的东西:
let user = null;
if (typeof window !== "undefined") {
user = JSON.parse(localStorage.getItem("user"));
} else {
// ... server-side logic
}
For other solutions see here: https://dev.to/vvo/how-to-solve-window-is-not-defined-errors-in-react-and-next-js-5f97对于其他解决方案,请参见此处: https : //dev.to/vvo/how-to-solve-window-is-not-defined-errors-in-react-and-next-js-5f97
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.