问题
用户登录后,用户详细信息保存在mobx状态。但是在页面刷新之后,这些数据消失了。我想持久化数据的mobx状态,使用户数据是留在mobx状态,直到用户注销。
我尝试了mobx-persistence-store,但当我转到另一个页面时,这些数据又消失了。如何在Next.js中实现持久性存储,有或没有mobx-persistent-store?
根存储提供者
import { createContext, FC, useContext } from "react";
import { RootStore } from "./root";
const RootStoreContext = createContext<RootStore>(new RootStore());
export const useStore = () => {
const context = useContext(RootStoreContext);
if (context === undefined) {
throw new Error("useStore must be used within StoreProvider");
}
return context;
};
let rootStore: RootStore | undefined;
const initializeStore = (initialData?: RootStore) => {
const _rootStore = rootStore ?? new RootStore();
if (initialData) {
_rootStore.hydrate(initialData);
}
if (typeof window === "undefined") return _rootStore;
if (!rootStore) rootStore = _rootStore;
return _rootStore;
};
interface Props {
children: React.ReactNode;
intialState?: RootStore;
}
export const RootStoreProvider: FC<Props> = ({ children, intialState }) => {
const store = initializeStore(intialState);
return (
<RootStoreContext.Provider value={store}>
{children}
</RootStoreContext.Provider>
);
};
字符串
rootStore
import { UserStore } from "./user";
import { hydrateStore, makePersistable } from "mobx-persist-store";
import localforage from "localforage";
export class RootStore {
user: UserStore;
constructor() {
this.user = new UserStore(this);
makePersistable(
this.user,
{
name: "RootStore",
properties: ["details", "cart"],
storage: typeof window !== "undefined" ? localforage : undefined,
},
{ delay: 200, fireImmediately: false }
);
}
async hydrate(data: RootStore): Promise<void> {
await hydrateStore(data);
}
}
型
1条答案
按热度按时间evrscar21#
我得让它在没有
localforage
软件包的情况下工作。我在您的实现中注意到的另一件事是在RootStore
中使用了makePersistable()
。它应该在您的UserStore
中,就像我下面的示例中那样:字符串