mobx 中的 @observable 和 @observable.ref 修饰符有什么区别?
Whats the difference between @observable and @observable.ref modifiers in mobx?
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.
我不明白为什么我们需要为一个已经存在的可观察对象创建一个可观察对象引用。这两个有何不同,它们的用例是什么?
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
我想解释一下 Ivan V. 的回答。
在他的代码中,test.reference
是一个引用,在重新赋值之前不会改变变量在内存中的地址。
push/pop 等操作或编辑 test.reference[0]
的值只是更改值而不是变量的引用。
所以当使用 @observable.ref 时,mobx 将比较变量的内存地址,当使用 @observable[=17 时,它是 observed.But =], mobx 会比较变量的值来决定触发反应。
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.
我不明白为什么我们需要为一个已经存在的可观察对象创建一个可观察对象引用。这两个有何不同,它们的用例是什么?
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
我想解释一下 Ivan V. 的回答。
在他的代码中,test.reference
是一个引用,在重新赋值之前不会改变变量在内存中的地址。
push/pop 等操作或编辑 test.reference[0]
的值只是更改值而不是变量的引用。
所以当使用 @observable.ref 时,mobx 将比较变量的内存地址,当使用 @observable[=17 时,它是 observed.But =], mobx 会比较变量的值来决定触发反应。