MobX:如何更改可观察值以响应另一个值的变化?

问题描述 投票:3回答:4

假设我有一个带有两个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;
}
javascript mobx
4个回答
3
投票

您可以使用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}`);

1
投票

此任务可以通过在存储构造函数中初始化的“when”进程完成:

class store(){
    constructor(){
     when (){
      ()=>{(this.country === 'US' && this.city === 'Paris')}
      ()=>{ this.city = ''}
    } 
  }
} 

可以在这里找到完整且有据可查的解释:https://mobx.js.org/refguide/when.html


1
投票

我认为你应该以不同的角度看待你的问题。

我问自己的问题是:你是不是可以做些什么来避免你完全面对的问题?

为什么要让情况首先发生?

  • 如果设置了国家/地区:为该国家/地区创建城市的子集。
  • 如果城市设置且国家/地区发生变化,请同时取消城市设置。

关于mobx特定模式,这些文档很有用:

根据经验:如果您有一个应该自动运行但不会产生新值的函数,请使用自动运行。使用计算用于其他一切。 Autoruns是关于启动效果,而不是关于产生新价值。 Mobx docs


0
投票
observe(state, "country", ({ oldValue, newValue }) => this.handleCountryChange(oldValue, newValue));


handleCountryChange = (oldValue, newValue) => {}
© www.soinside.com 2019 - 2024. All rights reserved.