假设我有一个包含两个 MobX @observable
字段的对象:
class Address {
@observable country
@observable city
}
当其中一个改变时,我想调用一个函数来改变另一个。例如,当 country
更改时,如果 city
的值对新国家/地区无效,我可能想清除它。
有好的模式吗?
我不认为我可以使用autorun
。由于我正在尝试更改可观察值,并且我已打开 enforceActions
,因此我需要在 action
中更改它。但这会引发错误“Autorun 不接受操作,因为操作无法跟踪”:
autorun(action(() => {
if (this.country === 'US' && this.city === 'Paris') this.city = '';
}));
我知道我可以添加一个返回 city
或新值的 @computed
函数。但是 city
的原始值仍然存在,并且会在 country
变回时返回。我不想要这个;我想永久更改城市
。
@computed get realCity() {
if (this.country === 'US' && this.city === 'Paris') return '';
return this.city;
}
最佳答案
你可以使用 observe观察构造函数中的对象,如果国家改变,则重置城市。
示例 ( JSBin )
class Address {
@observable country = 'Sweden';
@observable city = 'Stockholm';
constructor() {
observe(this, (change) => {
if (change.name === 'country') {
// Put your logic for changing the city here
this.city = '';
}
});
}
}
const address = new Address();
console.log(`${address.country}, ${address.city}`);
address.country = 'Spain';
console.log(`${address.country}, ${address.city}`);
关于javascript - MobX:如何改变一个可观察值以响应另一个值的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50746872/