0

我有两个模型/商店,每个都引用一个对象。Store2 在 Store1 被填充并接收到 childId 后被填充。当 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;
4

1 回答 1

1

如果Store2依赖于Store1任何东西,你最好在store2实例中引用它。然后,您可以简单地添加一个观察store1实例属性的视图,一旦观察到的属性更新,它将自动重新计算自身。

于 2019-05-08T16:55:43.533 回答