使用MobX验证对象的属性

时间:2017-03-23 04:25:05

标签: javascript reactjs mobx

假设我有这样一个类:

class Foo {
  @observable url;
}

如果url属性不是有效的网址,我想记录警告。我可以使用autorun收听url属性。当它发生变化并且它不再是有效的URL时,我可以记录警告。还有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

我认为,如果您只是想记录警告而不是为用户显示任何内容,那么您提到的解决方案是最好的。

示例

import isUrl from 'is-url';

class Foo {
  @observable url;
}

const foo = new Foo();

autorun(() => {
  if (isUrl(foo.url)) {
    console.warn(`${foo.url} is an invalid URL.`);
  }
});

答案 1 :(得分:0)

您可以使用observe or intercept。在intercept的情况下,如果网址无效,您甚至可以取消修改。

import {intercept} from 'mobx'

class Foo {
  @observable url;
}

const foo = new Foo();

intercept(foo, 'url', change => {
  const url = change.newValue;

  if (!isUrl(url)) {
    console.log(`'${url}' is invalid url`);
    return null; // cancel modification
  }
});

来自mobx-decorators@observe@intercept也可能对您有用。

import {intercept} from 'mobx-decorators'

class Foo {
  @intercept(change => {
    const url = change.newValue;

    if (!isUrl(url)) {
      console.log(`'${url}' is invalid url`);
      return null; // cancel modification
    }
  })
  @observable url;
}