题意:有没有办法在发生错误时防止用户重定向?
问题背景:
I have a simple signup form which works perfectly but I noticed when there is an error it still redirects to the homepage.
我有一个简单的注册表单,它工作得很好,但我注意到当出现错误时,它仍然会重定向到主页。
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);
}
};
//authStore.jsx
import { create } from "zustand";
const API_URI = "http://localhost:3001/api/auth";
export const useAuthStore = create((set) => ({
isLoading: false,
error: null,
isAuthenticated: false,
isCheckingAuth: false,
message: null,
user: null,
signup: async (email, password, name) => {
set({ isLoading: true, error: null });
try {
const options = {
credentials: "include",
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, name }),
};
const response = await fetch(`${API_URI}/signup`, options);
console.log(response);
if (!response.ok) {
const data = await response.json();
throw new Error(data.message);
}
const data = await response.json();
set({ user: data.user, isAuthenticated: true, isLoading: false });
} catch (error) {
set({
error: error.message || "Error signing up",
isLoading: false,
});
}
},
When I try to go back the browser and hit the button submit it will now prevent it from redirecting because the error is now being stored in the variable. I believe logic is true first before the error variable is stored. that's why! Is there a better way to do it? or how does the logic work?
当我尝试返回浏览器并点击提交按钮时,它将阻止重定向,因为错误现在被存储在变量中。我相信在错误变量存储之前,逻辑是正确的。这就是原因!有没有更好的方法来处理这个?或者说这个逻辑是如何工作的?
问题解决:
handleSignUp
has a stale closure over the error
value returned by the useAuthStore
hook.
`handleSignUp` 对 `useAuthStore` 钩子返回的 `error` 值存在陈旧的闭包。
I would suggest updating the signup
handler to throw errors out for callers to catch and handle. If no errors/exceptions are thrown then assume success, otherwise, catch and handle them appropriately.
我建议更新 `signup` 处理程序,将错误抛出,以便调用者捕获和处理。如果没有抛出错误/异常,则假定成功;否则,请适当地捕获并处理它们。
Example:
signup: async (email, password, name) => {
set({ isLoading: true, error: null });
try {
const options = {
credentials: "include",
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, name }),
};
const response = await fetch(`${API_URI}/signup`, options);
const data = await response.json();
set({ user: data.user, isAuthenticated: true, isLoading: false });
// Return data to caller
return data;
} catch (error) {
set({
error: error.message || "Error signing up",
isLoading: false,
});
// Re-throw error for caller
throw error;
}
},
const { signup, error, isLoading } = useAuthStore();
const navigate = useNavigate();
const handleSignUp = async (e) => {
e.preventDefault();
try {
await signup(email, password, name);
// const data = await signup(email, password, name);
// Success, navigate to home
navigate("/");
} catch (error) {
// Failure, handle error
console.log(error);
}
};