Is there a way to prevent user to redirect if there is an error?

题意:有没有办法在发生错误时防止用户重定向?

问题背景:

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

### 回答1: dropout是一种简单的方法,用于防止神经网络过度拟合。它通过在训练过程中随机地将一些神经元的输出设置为零,从而减少了神经元之间的依赖关系,使得网络更加鲁棒和泛化能力更强。这种方法可以有效地提高模型的性能,并且在实际应用中得到了广泛的应用。 ### 回答2: dropout是一种简单有效的防止神经网络过拟合的方法,其原理是在训练神经网络时随机选择一部分神经元不参与计算。具体来说,对于每个训练样本,我们以一定的概率(通常是50%)随机将其中一些神经元的输出设为0。这样做有两个好处:一是可以减少每个神经元的依赖性,从而使网络更加健壮,避免“依赖某些特定神经元”的问题;二是可以防止过拟合,因为每个神经元都有一定的概率被“关闭”,这样可以避免某些神经元在处理训练数据时过于自信,而在处理测试数据时失效。实际实现时,dropout可以在每个层之间添加dropout层或者在每个全连接层之前添加dropout操作。使用dropout时需要注意,dropout的概率不能过高,否则会使网络无法学习到足够的信息。同时,dropout在测试时需要关闭,因为在测试时我们需要利用所有的神经元进行最终的预测。总的来说,dropout是一种简单而有效的防止神经网络过拟合的方法,可以提高网络的泛化性能和鲁棒性。 ### 回答3: 随着深度学习的发展,人们逐渐意识到过拟合问题的严重性。为了解决这个问题,大量的复杂度更高的网络或方法被提出,如L1,L2正则化,数据增强,dropout等。本文将重点介绍dropout这种简单且有效的方法。 dropout是由Geoff Hinton在2012年提出的。其基本思想是在训练神经网络时,通过以概率p(通常为0.5)随机地使一些隐含层单元输出为0。而在预测时,dropout仅仅将所有的单元都保留下来,并将其输出乘以概率p,以避免模型过度依赖于任何一个单元。 dropout的实现方法非常简单,主要包括两个步骤。第一步是在训练时,以概率p决定哪些单元要被保留,哪些要被丢弃。第二步是在预测时,将所有的单元都保留下来,同时将其输出与概率p相乘。 dropout具有以下几个优点: 1. dropout可以显著减少过拟合。通过在模型中随机丢弃一些单元,可以有效地减少模型之间的相互依赖,避免复杂模型过度学习训练数据,从而提高泛化能力。 2. dropout可以提高模型学习速度。相比其他正则化方法,dropout的运算速度非常快,只需要在前向传播中做一些简单的随机化,不会对反向传播过程带来额外的复杂度。 3. dropout可以解决模型中的特征选择问题。dropout的随机丢弃可以促使每个神经元的输出都得到充分利用,即使是那些在训练集中很少出现的特征也会得到一定程度的学习,从而避免了一些过拟合问题。 总之,dropout是一种简单且实用的正则化方法,可以显著减少神经网络过拟合的问题,同时也具有很高的运行速度和模型准确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

营赢盈英

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值