gpt4 book ai didi

javascript - Mobx 状态树发生更改后如何让模型/状态进行监听?

转载 作者:行者123 更新时间:2023-12-02 23:41:48 24 4
gpt4 key购买 nike

我有两个模型/商店,每个模型/商店都引用一个对象。 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;

最佳答案

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

关于javascript - Mobx 状态树发生更改后如何让模型/状态进行监听?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56032601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com