Javascript 正在验证对象';使用MobX的s属性
假设我有一个这样的类:Javascript 正在验证对象';使用MobX的s属性,javascript,reactjs,mobx,Javascript,Reactjs,Mobx,假设我有一个这样的类: class Foo { @observable url; } 如果url属性不是有效的url,我想记录一条警告。我可以使用autorun收听url属性。当它更改并且不再是有效的URL时,我可以记录警告。有更好的方法吗?如果您只想记录警告而不向用户显示任何内容,我认为您提到的解决方案是最好的 示例 import isUrl from 'is-url'; class Foo { @observable url; } const foo = new Foo();
class Foo {
@observable url;
}
如果
url
属性不是有效的url,我想记录一条警告。我可以使用autorun
收听url
属性。当它更改并且不再是有效的URL时,我可以记录警告。有更好的方法吗?如果您只想记录警告而不向用户显示任何内容,我认为您提到的解决方案是最好的
示例
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.`);
}
});
你可以用。在拦截的情况下,如果url无效,您甚至可以取消修改
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
}
});
另外,来自的@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;
}