Javascript 异步函数中的反应设置状态
我使用以下异步函数通过REST服务验证有效的用户凭据Javascript 异步函数中的反应设置状态,javascript,reactjs,asynchronous,promise,Javascript,Reactjs,Asynchronous,Promise,我使用以下异步函数通过REST服务验证有效的用户凭据 async doesLoginExist(regCode) { if (loginCode.match(loginCodePattern)) { try { await LoginService.getUserByLoginCode(); return {}; } catch (err) { if (err.status === 404) {
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}对象返回给调用者,结果被用作屏幕上显示的验证消息。另一个小问题是自动聚焦在文本框中输入登录代码也不起作用
是否有其他方法可以在该函数中设置状态
doesginexist
正确绑定到组件的上下文。由于缺乏信息,无法确定,但这是一个非常常见的问题。
示例如何绑定DoesEngineExist本身-您必须在构造函数中显式地执行此操作
constructor() {
super();
this.doesLoginExist = this.doesLoginExist.bind(this);
}
async doesLoginExist() {
this.setState({ canProceed: false });
...
}
this.setState
调用从DoesEngineXist
提取到另一个方法,可以选择性地进行重构,这将提高DoesEngineXist
handleSomethingHappened = () => {
this.setState({ canProceed: false });
const result = await doesLoginExist(regCode)
this.setState({ canProceed: true });
}
doesginexist
正确绑定到组件的上下文。由于缺乏信息,无法确定,但这是一个非常常见的问题。
示例如何绑定DoesEngineExist本身-您必须在构造函数中显式地执行此操作
constructor() {
super();
this.doesLoginExist = this.doesLoginExist.bind(this);
}
async doesLoginExist() {
this.setState({ canProceed: false });
...
}
this.setState
调用从DoesEngineXist
提取到另一个方法,可以选择性地进行重构,这将提高DoesEngineXist
handleSomethingHappened = () => {
this.setState({ canProceed: false });
const result = await doesLoginExist(regCode)
this.setState({ canProceed: true });
}
干杯。为什么要用wait这个。setState?嗯,我想不需要了。然而,当我取出它的时候,同样的问题。你没有足够清楚地描述这个问题,什么“似乎不再正确地返回我的{error,success}”意思是?编辑了我的问题你为什么在这个问题上使用wait。setState?嗯,我想这是不必要的。但是当我取出它时出现了相同的问题。你没有足够清楚地描述这个问题,什么“似乎不再正确地返回我的{error,success}意思?编辑了我的问题