我构建了一个 React,现在我尝试从 React Router dom 迁移到 Next.js。我进行了重大更改并重构了代码;(pages/routes 和 store.js)但后来我收到此错误“ReferenceError:localStorage 未定义”。
19 | const initialState = {
> 20 | access: localStorage.getItem('access'),
| ^
21 | refresh: localStorage.getItem('refresh'),
22 | isAuthenticated: null,
23 | user: null
Run Code Online (Sandbox Code Playgroud)
你能帮我解决这个问题吗?
减速器/auth.js:
import {
LOGIN_SUCCESS,
LOGIN_FAIL,
SIGNUP_SUCCESS,
SIGNUP_FAIL,
ACTIVATION_SUCCESS,
ACTIVATION_FAIL,
USER_LOADED_SUCCESS,
USER_LOADED_FAIL,
AUTHENTICATED_SUCCESS,
AUTHENTICATED_FAIL,
PASSWORD_RESET_SUCCESS,
PASSWORD_RESET_FAIL,
PASSWORD_RESET_CONFIRM_SUCCESS,
PASSWORD_RESET_CONFIRM_FAIL,
LOGOUT
} from '../actions/types';
const initialState = {
access: localStorage.getItem('access'),
refresh: localStorage.getItem('refresh'),
isAuthenticated: null,
user: null
};
export default function (state = initialState, action) {
const { …Run Code Online (Sandbox Code Playgroud) 在我的NextJS应用中,我似乎无法访问window
未处理的拒绝(ReferenceError):未定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
Run Code Online (Sandbox Code Playgroud)
我目前正在使用 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"); …Run Code Online (Sandbox Code Playgroud) 在我的 Zustand 存储中,我尝试从本地存储中保存的数据加载初始状态(我没有选择中间件,因为 Next 存在一些我不想处理的问题):
const getInitialProject = (): Project => {
const project = loadCurrentProjectFromLs()
return (
project ?? {
projectName: '',
cards: [],
}
)
}
const useProjectStore = create<ProjectStore>((set, get) => ({
...getInitialProject(),
...
Run Code Online (Sandbox Code Playgroud)
然而,页面的第一次渲染是在服务器上完成的,而不是在客户端上完成的(在 React 和 Next.js 构造函数中,我收到“引用错误:本地存储未定义”),这意味着当时无法访问本地存储。
这意味着我的代码无法正常工作,因为状态只能在第一次渲染后更新,但导致 Zustand 初始化的钩子在第一次渲染期间被触发。
有没有比使用useEffect当 localStorage 变得可访问时更新存储的钩子更好的方法来解决这个问题?我希望逻辑成为商店的一部分,而不是客户端,但我想不出比带有计时器的循环更好的东西......