Mobx支持@observable和@ observable.ref修饰符,并且它们的官方文档说
observable: This is the default modifier, used by any observable. It clones and converts any (not yet observable) array, Map or plain object into it's observable counterpart upon assignment to the given property
observable.ref: Disables automatic observable conversion, just creates an observable reference instead.
我不明白为什么我们需要为已经存在的可观察对象创建可观察参考。这两个有什么不同?用例是什么?
答案 0 :(得分:1)
observable.ref
将仅跟踪对象的参考更改,这意味着您将需要更改整个对象才能触发反应。因此,例如,如果您有一个通过引用跟踪的可观察数组,那么将不会跟踪该数组的内容。同样,如果您将项目添加到数组中,更改也将不会被跟踪。
import { observable, reaction } from "mobx";
const test = observable(
{
reference: [{ id: 1 }]
},
{
reference: observable.ref
}
);
reaction(
() => {
return test.reference.length;
},
() => {
console.log("Reaction 1: reference length changed");
}
);
reaction(
() => {
return test.reference[0];
},
() => {
console.log("Reaction 2: reference item changed");
}
);
test.reference[0] = { id: 2 }; // this will not trigger the reactions
test.reference.push({ id: 3 }); // this will not trigger the reactions
test.reference.pop(); // this will not trigger the reactions
test.reference = []; // this will trigger both reactions