You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中登录状态校验代码单次触发却弹出两次alert的问题

Why Does My Alert Pop Twice Before Redirecting to Login?

Hey there, let's dig into why that alert is firing twice even though you only wrote it once. This is a super common gotcha with React, especially in newer versions, so here are the most likely reasons and how to fix them:

1. React 18 Strict Mode is Triggering Double Renders

If you're working in a development environment (the default for most React setups), React 18's Strict Mode intentionally runs component renders and certain hooks twice to catch accidental side effects. Since your alert and redirect logic is sitting directly in the component's render flow, it gets executed twice when Strict Mode is enabled.

Fix: Move Your Logic to useEffect

Wrap your token check and alert logic in a useEffect hook with an empty dependency array. This ensures it only runs once when the component mounts, even in Strict Mode:

import { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import Cookies from 'js-cookie';

function YourProtectedComponent() {
  const [needsLogin, setNeedsLogin] = useState(false);

  useEffect(() => {
    const tokenExists = Cookies.get('auth-token');
    if (!tokenExists) {
      alert('Please log in to continue');
      setNeedsLogin(true);
    }
  }, []); // Empty array = runs once on component mount

  if (needsLogin) {
    return <Navigate to='/login' />;
  }

  // Render your protected content here
  return <div>Welcome to the protected area!</div>;
}

2. Your Component is Being Rendered Multiple Times

Double-check where this component is used in your app. It might be accidentally rendered twice—for example:

  • Nested inside multiple parent components
  • Listed multiple times in your route configuration
  • Duplicated in your JSX (like having two <YourProtectedComponent /> tags somewhere)

Fix: Audit Component Usage

Do a quick search for your component's name across your codebase to make sure it's only rendered once where needed. For routes, ensure your Routes (React Router v6) or Switch (v5) setup isn't matching multiple routes to the same component.

3. Unintended Re-Renders from State/Props Changes

If your component has state or props that are updating unexpectedly, it might re-render multiple times, triggering your alert each time. For example, if a parent component is passing a changing prop that causes this component to re-mount.

Fix: Add Dependencies to useEffect (if needed)

If you need to re-run the token check when certain values change, add those values to the useEffect dependency array. If not, stick with the empty array to keep it a one-time check.


Content of the question comes from Stack Exchange, question author: dipansh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 14:47:45