假设我有这样一个类:
class Foo {
@observable url;
}
如果url
属性不是有效的网址,我想记录警告。我可以使用autorun
收听url
属性。当它发生变化并且它不再是有效的URL时,我可以记录警告。还有更好的方法吗?
答案 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;
}