MobX:从observable.map()引用对象

时间:2018-04-08 11:58:33

标签: javascript mobx

在使用MobX的observable.map()时,我发现存储在地图中的对象不再链接到原始对象:

import { useStrict, configure, autorun } from 'mobx';
import { observable, action, computed } from 'mobx';


configure({ enforceActions: true });

let user = {id: 1, name: "John"};

let myMap = observable.map();
myMap.set(user.id, user);
user.name = "Bill";
console.log(myMap.get(1).name); // John is printed, I expect Bill

如何获得与普通动态对象相同的行为?即有没有一种方法可以从以前存在的引用中更新observable.maps中的对象?

user = {id: 1, name: "John"};
let myClassicMap = {};
myClassicMap[user.id] = user;
user.name = "Bill";
console.log(myClassicMap[1].name); // Bill is printed as expected

修改

使用observable.map(values, { deep: false })我得到了通常的行为,但我不明白我是否在可观察性方面失去了一些东西。在下面的示例中,autorun不是由user.name的更改触发的,不应该是吗?

import { observable, autorun} from 'mobx';

let myMap = observable.map({}, {deep: false});
myMap.set(user.id, user);
autorun(() => console.log(myMap));
user.name = "Bill";

1 个答案:

答案 0 :(得分:1)

这是因为无论何时向深度数组添加内容,您放入的所有内容也都会被包装/转换为可观察的内容:

let user = {id: 1, name: "John"};

let myMap = observable.map();
myMap.set(user.id, user); //here user is turned into observeable object where all curent keys are tracked

如果你没有转向:{deep: false},那么这个物体就不会被包裹/变成可观察的物体,因此你所做的任何改变都是可见的但是这些改变不会被追踪到阵列本身的变化。因此不会触发任何重新渲染。

此外,请确保您在启用action()后执行configure({ enforceActions: true });内的所有内容:

import { useStrict, configure, autorun } from 'mobx';
import { observable, action, computed } from 'mobx';


configure({ enforceActions: true });

let user = {id: 1, name: "John"};

let myMap = observable.map();
action(() =>{
    myMap.set(user.id, user);
    user = myMap.get(1); //here we retrieved the observable object version of user.
    user.name = "Bill";
})()
console.log(myMap.get(1).name)