Async/await 不适用于 react js(hooks)



我正在尝试创建一个使用 react 钩子的反应应用程序。 在登录表单中,当用户提交表单时,电子邮件和密码被传递给handleClick功能。 该函数从服务器获取数据并显示在客户端,但响应始终未定义,并且在从服务返回之前被调用。 这是代码...

登录.js

import React, { useState, useEffect } from 'react';
import { Button, Form, Container, Row, Col } from 'react-bootstrap';
import './login.css'
import * as services from '../services'
function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleClick = async(e) => {
e.preventDefault();
console.log(email, password);
let res = await services.login(email, password);
console.log(res);
}    
return (
<Container>
<Row className="justify-content-md-center ">
<header><h2>Rao infotech workspace</h2></header>
</Row>
<Row className="justify-content-md-center form">
<Col md="auto">
<Form onSubmit={handleClick}>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" onChange={(e) => setEmail(e.target.value)} />
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
</Form.Group>
<Button variant="primary" type="submit" >
Submit
</Button>
</Form>
</Col>
</Row>
</Container>
);

}
export default Login;

服务.js

import axios from "axios";
const baseUrl = "http://localhost:4000/"; 
export function login(email, password) {
var body = {email: email, password: password}
axios.post(baseUrl + 'user/login', body)
.then((res)=>{
console.log("res in service", res);
return res;
})
}

我尝试使用 useEffect,但无法了解如何在 useEffect(( 中调用函数

你需要返回你的login函数:

export async function login(email, password) {
var body = {email: email, password: password}
return axios.post(baseUrl + 'user/login', body)
.then((res)=>{
console.log("res in service", res);
return res;
})
}

或者简单地说:

export async function login(email, password) {
var body = {email: email, password: password}
return axios.post(baseUrl + 'user/login', body);
}
import axios from "axios";
const baseUrl = "http://localhost:4000/"; 
export function login(email, password) {
var body = {email: email, password: password}
return new Promise((resolve, reject) => {
axios.post(baseUrl + 'user/login', body)
.then((res)=>{
console.log("res in service", res);
return resolve(res);
});
})
}

只需在服务中创建承诺,您的异步/等待将开始工作。

您的服务.js登录函数不返回承诺,因此您无法等待其结果

相关内容

  • 没有找到相关文章

最新更新