【问题标题】:Use MobX with React Context while using Mobx Persist Store?在使用 Mobx Persist Store 时使用 MobX 和 React Context?
【发布时间】:2023-03-11 22:50:02
【问题描述】:

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

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, PersistState, 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

【问题讨论】:

    标签: javascript reactjs mobx mobx-react mobx-persist


    【解决方案1】:

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

    在商店中使用toJSON() 来跟踪应该保存哪些属性:

    toJSON() {
        const { color, counter } = this
        return {
            color,
            counter,
        }
    }
    

    并在constructor() 下方添加localStorage 逻辑。首先,检查localStorage 是否包含最新值,如果有,则返回。

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

    constructor() {
        ...
        const name = "CounterStore"
        const storedJson = localStorage.getItem(name)
        if (storedJson) Object.assign(this, JSON.parse(storedJson))
        autorun(() => {
            localStorage.setItem(name, JSON.stringify(this))
        })
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 2020-08-24
      • 2019-08-15
      • 2019-01-19
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      相关资源
      最近更新 更多