我使用以下异步函数通过 REST 服务验证有效的用户凭据;
async doesLoginExist(regCode) {
if (loginCode.match(loginCodePattern)) {
try {
await LoginService.getUserByLoginCode();
return {};
} catch (err) {
if (err.status === 404) {
return {
error: 'Your login code is not recognized.', success: null
};
}
return {
error: 'Service is temporarily unavailable.', success: null
};
}
}
return {};
}
但是,当我尝试在此函数中设置某些状态时;
async doesLoginExist(regCode) {
await this.setState({ canProceed: false });
if (loginCode.match(loginCodePattern)) {
try {
await LoginService.getUserByLoginCode();
await this.setState({ canProceed: true });
return {};
} catch (err) {
if (err.status === 404) {
return {
error: 'Your login code is not recognized.', success: null
};
}
return {
error: 'Service is temporarily unavailable.', success: null
};
}
}
return {};
}
它似乎不再正确地将我的 {error, success} 对象返回给调用者,该对象最终被用作屏幕上显示的验证消息。另一个小问题是输入登录代码的文本框自动聚焦也不起作用。
我应该在此函数中设置状态的其他方式吗?
最佳答案
确保
doesLoginExist
正确绑定(bind)到组件的上下文。由于缺乏信息,不能肯定地说,但这是一个很常见的问题。 Read more here 示例如何绑定(bind)doesLoginExist
本身 - 您必须在构造函数中显式执行此操作constructor() { super(); this.doesLoginExist = this.doesLoginExist.bind(this); } async doesLoginExist() { this.setState({ canProceed: false }); ... }
可以选择将
doesLoginExist
中的this.setState
调用提取到另一个方法中进行重构,这将提高doesLoginExist
的可重用性handleSomethingHappened = () => { this.setState({ canProceed: false }); const result = await doesLoginExist(regCode) this.setState({ canProceed: true }); }
干杯。
关于javascript - 在异步函数中响应设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46787282/