React 寄存器错误不显示

react register errors not displaying

提问人:willm berchiche 提问时间:3/8/2023 最后编辑:Drew Reesewillm berchiche 更新时间:3/8/2023 访问量:101

问:

我正在链接 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
      })
javascript reactjs reactux jsx redux 工具包

评论

0赞 Drew Reese 3/8/2023
具体问题是什么?只是设置和/或呈现状态有问题吗?我在那里没有看到任何明显的问题。请编辑以更详细地澄清问题到底是什么。除了一个动作的调度,我没有看到任何相关的 redux 代码。如果您认为减速器是相关的,那么还请包括一个更完整的最小可重现示例errorsregister
0赞 willm berchiche 3/8/2023
帖子已更新。谢谢你的回复,请原谅我的尴尬,因为我是新来的。

答:

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