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

React中3秒后自动跳转页面失效问题求助

问题排查与解决方案

核心问题出在条件渲染的执行顺序上:

当redirecting状态为true时,组件会优先进入第一个if (redirecting || !userContext?.user)分支,返回提示文本组件,后续检查redirect的代码永远不会被执行——哪怕3秒后redirect被设为true,组件重新渲染时redirecting依然是true,第一个分支依然会优先触发。

修复方案一:调整条件判断顺序

将检查redirect的逻辑放在最前面,确保只要redirect为true,就优先执行跳转:

export default function Home() {
  const [redirect, setRedirect] = useState<boolean>(false);
  const [redirecting, setRedirecting] = useState<boolean>(false);

  const userContext = useContext(UserContext);

  useEffect(() => {
    const value: string | null = localStorage.getItem("user");
    if (!value) {
      return setRedirecting(true);
    }
    const user: User = JSON.parse(value ?? "");

    if (userContext) {
      userContext.setUser({
        ...user,
      });
    }
  }, [userContext]);

  useEffect(() => {
    if (redirecting) {
      const timer = setTimeout(() => {
        console.log("here 1")
        setRedirect(true)
      }, 3000);
      // 清理定时器,避免内存泄漏
      return () => clearTimeout(timer);
    }
  }, [redirecting]);

  // 优先检查跳转条件
  if (redirect) {
    console.log("here 2");
    return <Navigate to="/register" />;
  }

  if (redirecting || !userContext?.user) {
    return (
      <Container sx={{ my: 2 }}>
        <Typography variant="h5">
          You need to register to access this page.
        </Typography>
      </Container>
    );
  }

  return (
    <div>Home Content</div>
  );
}

修复方案二:同步更新redirecting状态

在触发跳转时,将redirecting设为false,让第一个条件分支不再生效:

useEffect(() => {
  if (redirecting) {
    const timer = setTimeout(() => {
      console.log("here 1")
      setRedirect(true);
      setRedirecting(false); // 同步关闭redirecting状态
    }, 3000);
    return () => clearTimeout(timer);
  }
}, [redirecting]);

额外优化

原代码未清理定时器,可能导致组件卸载后定时器仍在运行,引发内存泄漏——上述修复方案中已添加了定时器清理逻辑,建议保留。

内容的提问来源于stack exchange,提问作者Ritik Raj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:52:28