构建时未定义 localStorage。 Nextjs 和打字稿

localStorage is not defined when building. Nextjs and Typescript

我正在使用 Restcountries API 在 NextJs 中构建应用程序。我正在使用 redux 来模拟​​ cart/fav-list 组件。但是当我 运行 “构建”时,我遇到了一个错误,提示“localStorage is not defined”

import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "@redux-devtools/extension";
import thunk from "redux-thunk";
import { DefaultState } from "redux/reducers";
import reducer from "../reducers";

function saveToLocalStorage(state: DefaultState) {
  try {
    const localStorageState = JSON.stringify(state);
    localStorage.setItem("statePersist", localStorageState);
  } catch (e) {
    console.warn(e);
  }
}

function loadFromLocalStorage() {
  try {
    const localStorageState = localStorage.getItem("statePersist");
    if (localStorageState === null) return undefined;
    return JSON.parse(localStorageState);
  } catch (e) {
    console.warn(e);
  }
  return undefined;
}

const storeFactory = () => {
  const middlewares = [thunk];
  const reduxStore = createStore(
    reducer,
    loadFromLocalStorage(),
    composeWithDevTools(applyMiddleware(...middlewares))
  );
  reduxStore.subscribe(() => saveToLocalStorage(reduxStore.getState()));
  return reduxStore;
};

const midi = storeFactory();

export type Store = ReturnType<typeof storeFactory>;
export type RootState = ReturnType<typeof midi.getState>;
export default storeFactory;

您遇到的问题是因为服务器端未定义 localStorage(又名 window.localStorage)。下一个服务器呈现您的组件,因此当发生这种情况并且它试图访问 localStorage 时找不到它。您必须等到浏览器呈现它才能使用 localStorage。

对于您将来可能会使用 window 的其他用例,您可以检查是否 (typeof window !== 'undefined')` 这是一个很好的方法检查您是否在客户端与服务器上。

const ISSERVER = typeof window === "undefined";
if (!ISSERVER) localStorage.setItem(key, value);

或者另一种方法是使用 Next 的 dynamic imports with ssr: false,尽管这通常仅在涉及更多的用例时才需要(即,如果您要导入 chart/graph 库或使用 [=25 的类似库=]).