gpt4 book ai didi

javascript - 使此异步/等待逻辑正常工作时遇到问题

转载 作者:行者123 更新时间:2023-12-01 00:13:28 25 4
gpt4 key购买 nike

我的 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);
});
};

我将其作为 Prop 传递给我的一条路线

<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();
}

但是由于它是作为 Prop 传递的函数,我真的不明白如何在那里实现等待,我尝试将登录函数设置为异步,然后像这样等待 Prop

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();
}

你的函数应该是这样的

关于javascript - 使此异步/等待逻辑正常工作时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59927913/

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