在 Mobx 状态树发生变化后如何让 model/state 监听?

How to get model/state to listen after a change is made in Mobx state tree?

我有两个 models/stores 每个都引用一个对象。 Store1 在填充 Store1 并收到 childId 后填充 Store2。当 Store1 被填充时,我如何让 Store2 收听?

商店 1

import {action} from 'mobx'
import axios from "axios";
import {types} from "mobx-state-tree";

const Store1 = types.model('Store1', {
    id: types.number,
    name: types.string,
    description: types.string,
    childId: types.number
}).actions(self => ({
    onChange(name, value) {
        self[name] = value;
    },
    getInfo(id) {
        //API call that gets uses id and returns data
        self.id = data.id
        self.name = data.name
        self.description = data.description
        self.childId = data.childId
    },
}));

const store1 = Store1.create({
    id: 0,
    name: '',
    description: '',
    childId: 0
});
export default store1;

Store2(在 Store1 从 API 调用中获取 childId 之前无法填充)

import {action} from 'mobx'
import axios from "axios";
import {types} from "mobx-state-tree";

const Store2 = types.model('Store2', {
    id2: types.number,
    name2: types.string,
    description2: types.string
}).actions(self => ({
    onChange(name, value) {
        self[name] = value;
    },
    //should receive id from store1 childId
    getInfo(childId) {
        //api call that gets info and returns data
        self.id2= data.id
        self.name2 = data.name
        self.description2 = data.description
    },
}));

const store2 = Store2.create({
    id2: 0,
    name2: '',
    description2: ''
});
export default store2;

如果 Store2 依赖于 Store1 你最好在 store2 实例中引用它。然后,您可以简单地添加一个观察 store1 实例的 属性 的视图,一旦观察到的 属性 更新,它将 auto-recompute 本身。