gpt4 book ai didi

javascript - 使用 MobX 验证对象的属性

转载 作者:太空宇宙 更新时间:2023-11-04 15:52:59 25 4
gpt4 key购买 nike

假设我有一堂这样的课:

class Foo {
@observable url;
}

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

最佳答案

您可以使用observe or 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;
}

关于javascript - 使用 MobX 验证对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42967229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com