首页 > 解决方案 > 使这个异步/等待逻辑工作的麻烦

问题描述

我的 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 不会让我这样做

标签: javascriptreactjs

解决方案


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

你的功能应该是这样的


推荐阅读