我可以在NextJS中使用本地存储(redux-thunk)

iih3973s  于 2022-10-01  发布在  其他
关注(0)|答案(1)|浏览(178)

我无法使用文件Store.js中的本地存储。

生成页面时发生此错误。所有控制台日志都将显示在终端窗口中。

在Store.js中

import { createStore, combineReducers, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import {
  productDetailsReducer,
  productsReducer,
} from "./reducers/productsReducer";
import { cartReducer } from "./reducers/cartsReducer";

const reducer = combineReducers({
  products: productsReducer,
  productDetails: productDetailsReducer,
  cart: cartReducer,
});

let initialState = {
  cart: {
    cartItems: localStorage.getItem("cartItems")
      ? JSON.parse(localStorage.getItem("cartItems"))
      : [],
  }
};

const middleware = [thunk];

const store = createStore(
  reducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

export default store;
ecbunoof

ecbunoof1#

窗口没有在next.js中定义,因为它呈现在服务器中,您需要在使用本地存储之前检查窗口对象。检查的示例如下:

let initialState = {
    cart: {
      cartItems:  typeof window !== 'undefined' && localStorage.getItem("cartItems")
        ? JSON.parse(localStorage.getItem("cartItems"))
        : [],
    }
  };

如果您希望以更高效的方式创建存储,请遵循next.js提供的示例:Redux presist example

相关问题