假设我有一个带有两个MobX @observable
字段的对象:
class Address {
@observable country
@observable city
}
当其中一个发生变化时,我想调用一个改变另一个的函数。例如,当country
发生变化时,我可能想要清除city
,如果它的值对新国家无效。
这有一个很好的模式吗?
我认为我不能使用autorun
。因为我试图改变一个可观察的值,并且我打开了enforceActions
,我需要在action
中更改它。但这会引发错误“自动运行不接受操作,因为操作无法检测”:
autorun(action(() => {
if (this.country === 'US' && this.city === 'Paris') this.city = '';
}));
我知道我可以添加一个返回@computed
或新值的city
函数。但是city
的原始值仍然存在,并且当country
改变回来时将返回。我不想要这个;我想永久改变city
。
@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}`);
此任务可以通过在存储构造函数中初始化的“when”进程完成:
class store(){
constructor(){
when (){
()=>{(this.country === 'US' && this.city === 'Paris')}
()=>{ this.city = ''}
}
}
}
可以在这里找到完整且有据可查的解释:https://mobx.js.org/refguide/when.html
我认为你应该以不同的角度看待你的问题。
我问自己的问题是:你是不是可以做些什么来避免你完全面对的问题?
为什么要让情况首先发生?
关于mobx特定模式,这些文档很有用:
根据经验:如果您有一个应该自动运行但不会产生新值的函数,请使用自动运行。使用计算用于其他一切。 Autoruns是关于启动效果,而不是关于产生新价值。 Mobx docs
observe(state, "country", ({ oldValue, newValue }) => this.handleCountryChange(oldValue, newValue));
handleCountryChange = (oldValue, newValue) => {}