提问人:willm berchiche 提问时间:3/8/2023 最后编辑:Drew Reesewillm berchiche 更新时间:3/8/2023 访问量:101
React 寄存器错误不显示
react register errors not displaying
问:
我正在链接 Web 应用程序的正面和背面,在注册部分,我无法向 UI 显示验证和服务器错误消息。
当执行
错误的注册时,我得到 400 和 401 状态,我要播放的消息在 Axsioserror>response>data>error 中
问题可能出在JSXrendring或我的Reducer中?
我的组件:
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import "./Signup.css";
import Button from "../../components/ui/Button";
import { register } from "../../redux/reducers/authReducer";
import { useNavigate } from "react-router-dom";
const Signup = () => {
const dispatch = useDispatch();
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [errors, setErrors] = useState({});
const [password, setPassword] = useState("");
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
const isValid = validateForm();
if (!isValid) {
navigate("/");
return;
}
try {
await dispatch(register({ username, email, password }));
} catch (error) {
if (error.response && error.response.data && error.response.data.error) {
// Display error message to user
setErrors({ message: error.response.data.error });
} else {
console.error(error);
}
}
};
const validateForm = () => {
let errors = {};
let isValid = true;
// Validate email
if (!email) {
errors.email = "Email field is required";
isValid = false;
} else if (!/\S+@\S+\.\S+/.test(email)) {
errors.email = "Email address is invalid";
isValid = false;
}
// Validate password
if (!password) {
errors.password = "Password field is required";
isValid = false;
} else if (password.length < 6) {
errors.password = "Password must be at least 6 characters long";
isValid = false;
}
setErrors(errors);
return isValid;
};
return (
<div>
<h2 className="register">Register :</h2>
{errors.message && <span className="error">{errors.message}</span>}
{errors.email && <span className="error">{errors.email}</span>}
{errors.password && <span className="error">{errors.password}</span>}
<form onSubmit={handleSubmit} className="signup-form">
<input
type="text"
placeholder="User name"
value={username}
onChange={(event) => setUsername(event.target.value)}
/>
<input
type="email"
placeholder="Email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
<Button text="Submit" type="submit" submit />
</form>
</div>
);
};
export default Signup;
我的减速机:
export const register = createAsyncThunk(
"auth/register",
async ({ username, email, password }, { rejectWithValue }) => {
try {
console.log("signup action creator called");
const response = await axios.post(
"http://localhost:5000/api/auth/register",
{ username, email, password }
);
console.log("signup response:", response);
return response.data; // return the response data
} catch (error) {
console.log("signup error:", error);
return rejectWithValue(error.response.data);
}
}
);
.addCase(signin.rejected, (state, action) => {
state.loading = false;
state.isAuthenticated = false;
state.error =
action.payload.error || "Failed to sign in. Please try again."; // set error message from response data, or fallback to a generic message
toast.error(state.error); // display error message using React Toastify
})
答:
1赞
Drew Reese
3/8/2023
#1
createAsyncThunk
操作始终解决。如果您想要或关心异步操作是否成功,那么您将需要或需要解开已解决的 Promise。
有关更多详细信息,请参阅处理 Thunk 结果
例:
const handleSubmit = async (e) => {
e.preventDefault();
const isValid = validateForm();
if (!isValid) {
navigate("/");
return;
}
try {
await dispatch(register({ username, email, password })).unwrap();
} catch (error) {
if (error.response && error.response.data && error.response.data.error) {
// Display error message to user
setErrors({ message: error.response.data.error });
} else {
console.error(error);
}
}
};
评论
errors
register