javascript - 使这个异步/等待逻辑工作的麻烦
问题描述
我的 React app.js 中有以下功能
login = (email, password) => {
axios({
method: "post",
url: "http://localhost:3003/login",
data: qs.stringify({ email, password }),
headers: {
"content-type": "application/x-www-form-urlencoded;charset=utf-8"
}
})
.then(res => {
console.log(res);
//the accestoken is set as a cookie in order to check routes
Cookies.set("accesstoken", res.data.accesstoken);
//we have to check the accesstoken manually before redirecting it to login, or else it will allow navigate since its not a <PrivateRoute> component
isAuthenticated().then(result => {
if (result === true) {
this.setState(
{ isAuthenticated: true, authenticationChecked: true },
() => {
this.props.history.push("/");
}
);
} else {
this.setState({
isAuthenticated: false,
authenticationChecked: true
});
if (res.data == "Password not correct") {
console.log("me va a hacer un return del pass");
return "Password not correct";
} else if (res.data == "User doesnt exist") {
return "User doesnt exist";
}
}
});
})
.catch(err => {
console.log(err);
});
};
我作为道具传递给我的一条路线
<Route exact path="/login" render={(props) => <LoginPage login={this.login} {...props} />} />
尽管该函数有效,但它始终评估为未定义,因为它不等待返回
handleSubmit(event) {
const { email, password } = this.state;
var loginStatus = this.props.login(email, password);
console.log("estado del login");
console.log(loginStatus); //this always evaluates to undefined, even if the return happens
if (loginStatus == "Password not correct") {
this.setState({
wrongPassword: true
});
} else if (loginStatus == "User doesnt exist") {
this.setState({
wrongUser: true
});
}
event.preventDefault();
}
但是由于它是作为道具传递的函数,我真的不明白如何在那里实现等待,我尝试将登录函数设置为异步,然后像这样等待道具
const loginStatus = await this.props.login(email, password)
但是 React 不会让我这样做
解决方案
async handleSubmit(event) {
const { email, password } = this.state;
var loginStatus = await this.props.login(email, password)
console.log("estado del login")
console.log(loginStatus); //this always evaluates to undefined, even if the return happens
if (loginStatus == "Password not correct"){
this.setState({
wrongPassword : true
})
}else if(loginStatus == "User doesnt exist"){
this.setState({
wrongUser : true
})
}
event.preventDefault();
}
你的功能应该是这样的
推荐阅读
- python - 在 google-apps-engine 中初始化和更改 ndb 属性
- google-app-engine - 即使在定义了 dispatch.yaml 之后,应用引擎灵活的 http 请求仍然会将用户带到默认服务
- jquery - 如何在悬停时加速 jQuery 替换图像
- c# - Visual Studio 项目 mdf
- android - 如何将事件侦听器添加到 RatingBar
- ag-grid - 从 ag-grid 导出的 excel 格式不正确
- jira - JIRA:CURL 命令的 Rest API 身份验证
- javascript - 在 node.js 中实现嵌套异步调用
- mono - Ubuntu 16.4:monodoc 不起作用(缺少 libgluezilla)
- math - 8T(n/2) +n^2 的树方法