未定义localStorage-使用Next.js反冲

6rqinv9w  于 2022-11-05  发布在  其他
关注(0)|答案(2)|浏览(146)

根据Recoil文档,我使用了localstorage效果,但是当我运行我的应用程序时,我在浏览器中得到了localStorage is not defined错误。我的第一个假设是这不是在浏览器和服务器中运行的。我不认为这是事实,除非Next.js在幕后做了一些时髦的事情?
下面是我的代码:
project/recoil/atom.ts

const localStorageEffect = (key: string) => ({setSelf, onSet}: {setSelf: any, onSet: any}) => {
  const savedValue = localStorage.getItem(key)
  if (savedValue != null) {
    setSelf(JSON.parse(savedValue));
  }

  onSet((newValue: any, _: null, isReset: any) => {
    isReset
      ? localStorage.removeItem(key)
      : localStorage.setItem(key, JSON.stringify(newValue));
  });
};

export const userAtom = atom({
  key: 'userAtom',
  default: {},
  effects: [
    localStorageEffect('user'),
  ]
});

我尝试使用它来保持登录状态。下面是我使用它的一个示例:
project/pages/login.tsx

const LoginPage = () => {
  const [address, setAddress] = useState('');
  const setUser = useSetRecoilState(userAtom);
  const setIsAuthed = useSetRecoilState(isAuthedAtom);

  const submitHandler = async (e: any) => {
    try {
      const walletInfo = await fetchWallet(address);
      setIsAuthed(true);
      setUser({...walletInfo, address});

    } catch(e: any) {
      console.log(e);
    }
  };

  return (
    <Login address={address} setAddress={setAddress} submitHandler={submitHandler} />
  )

下面是_app.tsx

import type { AppProps } from 'next/app';
import {
  RecoilRoot
} from 'recoil';
import '../styles/globals.css';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <RecoilRoot>
      <Component {...pageProps} />
    </RecoilRoot>
  );
}

export default MyApp;

但是,在加载主页时,由于出现错误信息,什么都不会呈现。我读到过一个解决方案,就是在useEffect钩子中运行这个,但是我不能这样做,因为我的效果是在atoms.ts中定义的,不能移动。有没有办法强制这个文件在浏览器中运行?

2hh7jdfx

2hh7jdfx1#

你可以试试这个对我很有效

import { recoilPersist } from 'recoil-persist'

const localStorage = typeof window !== `undefined` ? window.localStorage : null

const { persistAtom } = recoilPersist({
    key: 'recoil-persist',
    storage: localStorage
})

export const darkModeState = atom<true | false >({
    key: 'darkMode',
    default: false,
    effects_UNSTABLE: [persistAtom]
})
cbwuti44

cbwuti442#

您不需要安装任何其他库,只需替换以下部分:

import { AtomEffect } from 'recoil';

const store = typeof window !== 'undefined' ? window.localStorage : null;

export const localStorageEffect: (key: string) => AtomEffect<any> =
  (key) =>
  ({ setSelf, onSet }) => {
    if (store) {
      const savedValue = store.getItem(key);
      if (savedValue != null) {
        setSelf(JSON.parse(savedValue));
      }

      onSet((newValue, _, isReset) => {
        isReset ? store.removeItem(key) : store.setItem(key, JSON.stringify(newValue));
      });
    }
  };

相关问题