如何在useRoutes钩子的子组件中使用Route组件?
解决页面内使用Route组件渲染模态框的报错问题
报错原因很明确:单独的<Route>必须作为<Routes>的子元素,不能直接渲染。下面给你两种不用把模态框路由加到全局useRoutes数组里的解决方案:
方案一:在页面内用<Routes>包裹<Route>
直接在MyPage里把模态框的<Route>放到<Routes>组件中,既符合React Router的规则,又能把模态框路由逻辑留在页面内部维护:
import { Routes, Route } from 'react-router-dom'; function MyPage() { return ( <> <div>List of items</div> <Routes> <Route path="/myPage/:id" element={<Modal>Detail View</Modal>} /> </Routes> </> ); }
当访问/myPage/:id时,MyPage会正常渲染(父路由匹配),同时模态框也会在页面内渲染出来。
方案二:用useMatch钩子条件渲染模态框
如果模态框数量多,不想写一堆<Route>,可以用useMatch判断当前路由是否匹配,直接条件渲染模态框:
import { useMatch } from 'react-router-dom'; function MyPage() { const isModalPath = useMatch('/myPage/:id'); return ( <> <div>List of items</div> {isModalPath && <Modal>Detail View</Modal>} </> ); }
如果有多个不同的模态框路由,还能结合useParams获取参数区分渲染内容:
import { useMatch, useParams } from 'react-router-dom'; function MyPage() { const isModalPath = useMatch('/myPage/:modalType/:id'); const { modalType, id } = useParams(); return ( <> <div>List of items</div> {isModalPath && modalType === 'detail' && <DetailModal id={id} />} {isModalPath && modalType === 'edit' && <EditModal id={id} />} </> ); }
两种方案都不需要修改全局的useRoutes配置,模态框的路由逻辑都在MyPage内部维护,不会让全局路由数组变得臃肿难维护。
内容的提问来源于stack exchange,提问作者Amin
相关产品推荐
相关产品推荐

