使用 Mobx Persist Store 时将 MobX 与 React Context 一起使用?

问题描述

最初,我在 new CounterStore 中使用 React.createContext()

context.ts

import React from 'react'
import { stores,PersistState,CounterStore } from '@/store/index'
import type { ICounterStore } from '@/types/index'

export const FrameItContext = React.createContext<ICounterStore>(new CounterStore())
export const useCounterStore = () => React.useContext(FrameItContext)

然后我开始在我的应用中使用 Mobx Persist Store

persist.ts

import { persistence,StorageAdapter } from 'mobx-persist-store'
import { CounterStore } from '@/store/index'

const read = (name: string): Promise<string> =>
    new Promise((resolve) => {
        const data = localStorage.getItem(name) || '{}'
        console.log('got data: ',data)
        resolve(data)
    })

const write = (name: string,content: string): Promise<Error | undefined> =>
    new Promise((resolve) => {
        localStorage.setItem(name,content)
        console.log('write data: ',name,content)
        resolve(undefined)
    })

export const PersistState = persistence({
    name: 'CounterStore',properties: ['counter'],adapter: new StorageAdapter({ read,write }),reactionoptions: {
        // optional
        delay: 2000,},})(new CounterStore())

我将代码更改为使用 PersistState 而不是 new CounterStore()

context.ts

import React from 'react'
import { stores,CounterStore } from '@/store/index'
import type { ICounterStore } from '@/types/index'

export const FrameItContext = React.createContext<ICounterStore>(PersistState)
export const useCounterStore = () => React.useContext(FrameItContext)

它只将 got data: {} 记录到控制台。 write 函数永远不会被调用

我做错了什么吗?

巧合的是,CodesandBox 上的一个简单的 Counter 示例运行良好 → https://codesandbox.io/s/mobx-persist-store-4l1dm

解决方法

上面的示例适用于简单的 Chrome 扩展程序或网络应用程序,但似乎不适用于我的特定应用程序,因此我编写了保存到 LocalStorage 的手动实现。

在商店中使用 if [[ condition ]]; then echo "bash ${CommandLine}" | at now + ${Interval} minutes fi echo 'hello' 来跟踪应该保存哪些属性:

toJSON()

并在 toJSON() { const { color,counter } = this return { color,counter,} } 正下方添加 localStorage 逻辑。首先,检查 constructor() 是否包含最新值,如果包含则返回。

如果没有保存,则将其保存在localStorage中。

localStorage

代码沙盒 → https://codesandbox.io/s/mobx-persist-store-manual-implementation-vm38r?file=/src/store.ts