reactjs 如何在NextJS上持久化Mobx数据

chhkpiq4  于 2023-08-04  发布在  React
关注(0)|答案(1)|浏览(147)

问题

用户登录后,用户详细信息保存在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);
  }
}

evrscar2

evrscar21#

我得让它在没有localforage软件包的情况下工作。我在您的实现中注意到的另一件事是在RootStore中使用了makePersistable()。它应该在您的UserStore中,就像我下面的示例中那样:

import { makeObservable, observable, action } from "mobx"
import { makePersistable } from 'mobx-persist-store';

export class UserStore {

    id: string = ""
    email: string = ""
    firstName: string = ""
    lastName: string = ""
    phone: string = ""
    loggedIn: boolean = false
    registrationComplete: boolean = false

    constructor(initialData: any = {}) {
        makeObservable(this, {
            id: observable,
            email: observable,
            firstName: observable,
            lastName: observable,
            phone: observable,
            loggedIn: observable,
            registrationComplete: observable,
            setEmail: action,
            setFirstName: action,
            setLastName: action,
            setPhone: action
        })

        makePersistable(this, { 
            name: 'UserStore',
            storage: typeof window !== "undefined" ? window.localStorage : undefined,
            properties: [
                'id', 
                'email', 
                'firstName', 
                'lastName', 
                'phone',
                'loggedIn',
                'registrationComplete'
            ]
        })
        
        this.id = initialData.id
        this.email = initialData.email
        this.firstName = initialData.firstName
        this.lastName = initialData.lastName
        this.loggedIn = initialData.loggedIn
        this.registrationComplete = initialData.registrationComplete
    }

    setId(id: string) {
        this.id = id
    }

    setEmail(email: string) {
        this.email = email
    }

    setFirstName(firstName: string) {
        this.firstName = firstName
    }

    setLastName(lastName: string) {
        this.lastName = lastName
    }

    setPhone(phone: string) {
        this.phone = phone
    }

    setLoggedIn(loggedIn: boolean) {
        this.loggedIn = loggedIn
    }

    setRegistrationComplete(registrationComplete: boolean) {
        this.registrationComplete = registrationComplete
    }

    logout() {
        this.id = ""
        this.email = ""
        this.firstName = ""
        this.lastName = ""
        this.phone = ""
        this.loggedIn = false
        this.registrationComplete = false
    }

    __data() {
        return {
            id: this.id,
            email: this.email,
            firstName: this.firstName,
            lastName: this.lastName,
            phone: this.phone,
            loggedIn: this.loggedIn,
            registrationComplete: this.registrationComplete
        }
    }
}

字符串

相关问题