其他分享
首页 > 其他分享> > MobX store 基于另一个 store 做出 reaction

MobX store 基于另一个 store 做出 reaction

作者:互联网

目录

背景

最近遇到一个问题:我们每个域(Domain)都维护自己的一个 MobX store,通常情况下不需要和其他 store 产生联系。比如我们是搜索引擎组(相当于一个域),只需要维护自己的 store 就行了。

但突然有个需求,需要我们这个 store 和用户账户组(另一个域)的 store 产生联系:当用户在同一个账户下切换使用者子账户时(比如一家几口人共用一个账户,但有各自的使用者子账户),我们就要加载相应子账户的搜索历史记录。

简单来说就是:在用户账户 store 中表示子账户的那个值发生变化时,我们搜索引擎 store 中的搜索历史记录就需要重新加载了。

那么,如何实现这个需求呢?

RootStore 模式

首先,为了能够基于另一个 store 的状态来触发事件,首先需要能够访问另一个 store。

应该有不止一种方法可以实现这个目的,但 MobX 官网 推荐的方式是 RootStore 模式

简单来说就是,每个真正使用的 store 都是 rootStore 的一个属性,而它们又都把 rootStore 作为自己的一个属性来储存:

class RootStore {
    constructor() {
        this.fooStore = new FooStore(this)
        this.barStore = new BarStore(this)
    }
}

class FooStore {
    constructor(rootStore) {
    	// 可以通过 this.rootStore.barStore 来访问 barStore
        this.rootStore = rootStore
    }
}

class BarStore {
    constructor(rootStore) {
    	// 可以通过 this.rootStore.fooStore 来访问 fooStore
        this.rootStore = rootStore
    }
}

这样一来,通过 rootStore 这个中介,每个 store 就都可以访问到其他任何一个 store 了。

Reaction

那么如何根据另一个 store 中某个值的变化,触发本 store 的事件呢?

只需要使用最基础的 reaction 就可以了。类似于下面这样:

class RootStore {
    constructor() {
        this.fooStore = new FooStore(this)
        this.barStore = new BarStore(this)
    }
}

class FooStore {
    constructor(rootStore) {
        this.rootStore = rootStore

		reaction(
			// 第一个参数是一个函数,返回你想监测的值
			// 在这里就是另一个 store 的 someValue
            () => this.rootStore.barStore.someValue,
            (value) => {
            	// 根据更新之后的值,执行一些逻辑
            }
        );
    }
}

class BarStore {
	public someValue

    constructor(rootStore) {
    	makeAutoObservable(this, {
	      someValue: observable,
	    });
        this.rootStore = rootStore
    }
}

参考链接

MobX 官网:Combining multiple stores
In mobX can a store “listen” to other another store, and execute a query whenever the other store changes?
Running side effects with reactions

标签:reaction,barStore,RootStore,MobX,constructor,rootStore,class,store
来源: https://blog.csdn.net/VoisSurTonChemin/article/details/122762220