有没有办法阻止用户在出现错误时重定向?

问题描述 投票:0回答:1

我有一个简单的注册表单,效果很好,但我注意到当出现错误时它仍然会重定向到主页。

import { Loader, Lock, Mail, User } from "lucide-react";
import React, { useState } from "react";
import { motion } from "framer-motion";
import Input from "../components/Input";
import { Link, useNavigate } from "react-router-dom";
import PasswordStrengthMeter from "../components/PasswordStrengthMete";
import { useAuthStore } from "../store/auth.store";

export const SignUpPage = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const { signup, error, isLoading } = useAuthStore();
  const navigate = useNavigate();

  const handleSignUp = async (e) => {
    e.preventDefault();
    try {
      await signup(email, password, name);
     if(!error){
      navigate("/");
     }
    } catch (error) {
      console.log(error);
    }
  };

当我尝试返回浏览器并点击“提交”按钮时,它现在将阻止它重定向,因为错误现在存储在变量中。有更好的方法吗?或者逻辑是如何运作的?

javascript reactjs error-handling
1个回答
-1
投票

交叉检查

Error variable

的数据类型
  1. 字符串错误:“文本”
if (!error) { 
 // do something
}
  1. 对象错误:{消息:“文本”}
if (Object.keys(error).length === 0) { 
 // do something
}
  1. 数组(错误:[]或[{状态:“文本”}])
if (Object.keys(error).length === 0) { 
 // do something
}
© www.soinside.com 2019 - 2024. All rights reserved.