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

标签 javascript reactjs

我的 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/

相关文章:

javascript - 从 NodeJS/Express 发送 JSON 响应

javascript - 继承后无法构造 Javascript 对象(在对象内)

javascript - 跨现代浏览器有条件地定义函数?特别是 Safari ?

reactjs - 有没有一种简单的方法可以使用 Apollo Client 2.5 for React 管理本地状态? 'read' 相当于 'client.writeData' 是什么?

javascript - 将 props 附加到 props 的无状态函数上

reactjs - Material-UI useAutocomplete 无法访问 onChange 中的选项

php - 在网站中使用等待光标好吗?

php - 发送表单后如何在不刷新页面的情况下重新加载元素的内容(蛋糕方式)?

javascript - React 组件无法同步由动态 ReactDOM.render 创建的 props

javascript - 只影响导入样式的组件的样式?