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

如何修复React中Cannot render a <Router> inside another <Router>错误?

解决React中"You cannot render a inside another "错误

错误原因

你的代码同时在两个层级渲染了路由容器组件:

  • index.js中用<Router>(即BrowserRouter的别名)包裹了整个<App>
  • App.js的返回值里又嵌套了<BrowserRouter>

react-router-dom要求整个应用只能有一个顶层路由容器,嵌套多个会导致路由逻辑冲突,触发该报错。

修复方案(二选一即可)

方案1:移除App.js中的<BrowserRouter>

保留index.js的顶层Router,删除App.js最外层的<BrowserRouter>——因为App已经处于index.js的Router上下文范围内,内部不需要再嵌套路由容器。

修改后App.js的return部分代码:

return (
  <div className="container">
    <Navbar />
    <Routes>
      <Route path="/" element={<h1>Welcome to the Product Manager</h1>} />
      <Route path="/product-types" element={
        <>
          <ProductTypeList productTypes={productTypes} onDeleteProductType={handleDeleteProductType} />
          <ProductTypeForm onAddProductType={handleAddProductType} />
        </>
      } />
      <Route path="/product-types/:id" element={<ProductTypeForm productTypes={productTypes} onUpdateProductType={handleUpdateProductType} />} />
      <Route path="/products" element={
        <>
          <ProductList products={products} onDeleteProduct={handleDeleteProduct} />
          <ProductForm productTypes={productTypes} onAddProduct={handleAddProduct} />
        </>
      } />
      <Route path="/products/:id" element={<ProductForm productTypes={productTypes} onUpdateProduct={handleUpdateProduct} />} />
    </Routes>
    <button onClick={handleButtonClick}>Go to Product Types</button>
  </div>
);

方案2:移除index.js中的<Router>

如果希望把路由容器放在App.js内部,那么删除index.js中的<Router>包裹,直接渲染App组件:

修改后index.js的渲染代码:

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

注意事项

react-router-dom的路由系统依赖单一顶层Router提供上下文,所有使用useNavigate、Routes、Route等路由相关API的组件,都必须处于这个顶层Router的子组件树中,不能同时存在多个Router实例。

内容的提问来源于stack exchange,提问作者Abdelmoula Bilel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:59:57