Mobx在非react组件中修改数据,在ts/js中修改数据实现响应式更新

我们都之前在封装mobx作为数据存储的时候,使用到了useContext作为包裹,将store变成了一个hooks使用,封装代码:

import React from 'react'
import UserInfo from './user'
import Setting from './seting'
import NoteStore from './note'

class Store {
    userInfo: UserInfo
    setting: Setting
    noteActive: NoteStore

    constructor() {
        this.userInfo = new UserInfo()
        this.setting = new Setting()
        this.noteActive = new NoteStore()
    }
}

// 使用context是为了让react识别到Store里面的mobx,不然react不认识Store
export const rootStore = new Store()
const context = React.createContext(rootStore)
export const useStore = () => React.useContext(context)
export default useStore

但是我们都知道hooks只能在函数组件中或者hooks中使用,不能在ts/js代码中使用,但是我这里有一个需求,想每次发送接口请求的时候,做一个后置处理器,用于获取接口使用率和剩余次数,并且在界面上实时更新。

这就需要我们在接口请求的js/ts中去更新这个mobx中的接口数据,实现响应式更新。这个时候就不能使用useContext了,因为它只能在函数组件中或者hooks中使用。这个时候就要我们单独使用rootStore这个对象,然后使用这个对象里面的userInfo的store,再调用里面修改数据的方法:

import { rootStore } from '@/store'


.....



// 导入或创建你的 MobX store 对象
const { userInfo } = rootStore



....


// 重新获取API接口速率
export const getApiLimit = () => {
    let payload = {
        method: 'GET' as HttpVerb,
        headers: {
            Authorization: `Bearer ${localStorage.getItem('token') || ''}`,
            'User-Agent': 'PostmanRuntime/7.32.3',
        },
    }
    fetch('https://api.github.com/rate_limit', payload)
        .then(({ status, data }) => {
            if (status >= 200 && status < 500) {
                console.log('apilimit---', data)
                userInfo.setApiLimit((data as any).rate)
            }
        })
        .catch((err) => {
            console.error('apilimiterr-------', err)
        })
}

引入这个userInfo的store: 

调用修改数据的函数:

然后在需要使用数据的组件中,将组件变成可以侦听的组件:

最后就可以在界面上发现,数据已经可以同步响应式了:

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/132467766