我是开发人员的新手,我正在尝试通过以下方式在react功能组件中使用try catch:
import { useState } from "react";
import Container from "react-bootstrap/Container";
import { Row, Col, Form, Button } from "react-bootstrap";
import { useHistory } from "react-router-dom";
import Input from "../Input/Input";
import AuthenticationServices from "../../services/AuthenticationServices";
const SignIn = () => {
const [userData, setUserData] = useState({});
const {
firstName,
lastName,
email,
password,
repeatPassword,
error,
} = userData;
const onChange = (e) => {
setUserData({
...userData,
[e.target.name]: e.target.value,
});
};
const onSubmit = () => {
try {
if (password === repeatPassword) {
AuthenticationServices.register({
firstName: firstName,
lastName: lastName,
email: email,
password: password,
});
} else {
setUserData({
...userData,
error: "Passwords don't match",
});
}
} catch (err) {
console.log(err);
setUserData({
...userData,
error: err.response.data.error,
});
}
};
return (
<Container
fluid
className="mx-auto p-5"
style={{ backgroundColor: "#ddd" }}
>
<Row>
<Col>
<Form
onSubmit={(e) => {
e.preventDefault();
onSubmit(e);
}}
>
<Input
label="Your name"
placeholder="Insert your name"
type="string"
value={firstName}
name="firstName"
idNumber="0"
onChange={(e) => onChange(e)}
required={true}
maxLength="5"
></Input>
...
路由器通过运行AuthenticationController.register在注册页面上管理发布请求
AuthenticationController.register方法包含:
try {
const user = await User.create(req.body); // Creates a new user using the user model
const userJSON = user.toJSON(); // Converts the user to JSON
res.send({
user: userJSON,
});
} catch (err) {
res.status(400).send({
error: `ERROR: Email already in use.`,
});
}
},
此刻,我可以通过设置userData.error:"Passwords don't match"
在div中显示“密码不匹配”。
该数据库接受唯一的电子邮件,在重复发送电子邮件的情况下,我尝试使用try catch来捕获错误,但是从我在组件中看到的信息来看,它根本无法捕获错误。
我使用postmain对其进行了测试,并且在重复发送电子邮件的情况下,我收到“错误:电子邮件已在使用中”的提示。符合预期
答案 0 :(得分:0)
我在同事的帮助下解决了这个问题。
不幸的是,我不知道异步等待如何工作,所以我花了一段时间。
我在运行try catch时没有等待AuthenticationServices.register的答复,因此它在接收到答复/错误之前退出了该功能。
这是正确的版本。
const onSubmit = async () => {
try {
if (password === repeatPassword) {
await AuthenticationServices.register({
firstName: firstName,
lastName: lastName,
email: email,
password: password,
});
redirect();
/*.then(redirect)
.catch((err) => {
console.log(err);
setUserData({
...userData,
error: err.response.data.error,
});
});*/
} else {
setUserData({
...userData,
error: "Passwords don't match",
});
}
} catch (err) {
console.log(err);
setUserData({
...userData,
error: err.response.data.error,
});
}
};