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

React受保护路由测试中返回Navigate引发无限循环问题排查

测试受保护路由时出现无限循环的问题分析与解决

问题根源

你的测试代码存在两个核心问题,直接导致了无限循环:

  1. 路由结构不完整:测试中直接将ProtectedRoute放在MemoryRouter中,未用Routes和Route定义路径映射。当ProtectedRoute因user=null跳转到/auth时,React Router找不到匹配的路由组件,触发重复导航逻辑,形成循环。
  2. 未将Auth组件挂载到对应路由:测试里没有把Auth组件配置到/auth路径下,跳转/auth后无组件渲染,Router导航状态异常,进而触发ProtectedRoute再次跳转。

你怀疑的Auth组件内useEffect并非问题原因——测试中currentUser始终为null,该useEffect根本不会执行。

修复后的测试代码

调整测试代码,补充完整路由结构:

it("redirects to auth when user is not logged in", () => {
  const currentUser = null;
  render(
    <UserContext.Provider value={{ currentUser, setCurrentUser }}>
      <MemoryRouter initialEntries={["/profile"]}>
        <Routes>
          {/* 配置受保护的/profile路由 */}
          <Route 
            path="/profile" 
            element={
              <ProtectedRoute user={currentUser}>
                <Profile />
              </ProtectedRoute>
            } 
          />
          {/* 配置/auth路由,挂载Auth组件 */}
          <Route path="/auth/*" element={<Auth />} />
        </Routes>
      </MemoryRouter>
    </UserContext.Provider>
  );
  expect(screen.getByText(/sign in/i)).toBeInTheDocument();
});

额外说明

  • 使用initialEntries={["/profile"]}指定测试初始路由,模拟用户访问受保护页面的场景。
  • Route的path="/auth/*"用于匹配Auth组件内部的子路由(如/auth/sign-up),确保跳转后能正确渲染登录/注册页面。
  • 实际应用无此问题,是因为生产环境已配置完整路由结构,所有导航路径都有对应组件挂载。

内容的提问来源于stack exchange,提问作者Le Moi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:57:28