React嵌套路由中子组件无法显示的问题排查与解决
Ah, I see the issue here—this is a common pitfall with React Router v6's nested routing system. Let's break down what's going wrong and how to fix it.
Root Cause
The problem stems from how you've configured the nested routes:
- In
App.js, the/homeroute is set to only match the exact path/home(since it has no child routes defined), so when you navigate to/home/news, theHomecomponent isn't properly rendered to begin with. - Inside
Home/index.js, you're using an absolute path (/home/news) for the child route, but without the parent route being set up to handle subpaths, this route never gets triggered correctly.
Solution 1: Use Nested Routes with <Outlet> (Recommended)
This is the standard, cleanest way to handle nested routes in React Router v6:
- Update
App.jsto define theNewsroute as a child of theHomeroute:
import './App.css'; import {BrowserRouter as Router,Route,Link,Routes} from 'react-router-dom' import {Button} from 'antd-mobile' import Home from './pages/Home' import CityList from './pages/CityList' import News from './pages/News'; // Import the News component import React from 'react'; function App() { return ( <Router> <div className="App"> <ul> <li><Link to='/home'>home</Link></li> <li><Link to='/citylist'>citylist</Link></li> <li><Link to='/home/news'>News</Link></li> {/* Add a direct link to News */} </ul> <Routes> <Route path='/home' element={<Home/>}> {/* Nest the News route under Home */} <Route path='news' element={<News/>}/> </Route> <Route path='/citylist' element={<CityList/>}/> </Routes> </div> </Router> ); } export default App;
- Update
Home/index.jsto use<Outlet>as a placeholder where the child component (News) will render:
import React from 'react' import {Outlet} from 'react-router-dom' // Import Outlet export default class Home extends React.Component { render(){ return( <div style={{backgroundColor:'skyblue',padding:10}}> home {/* Outlet renders the child route component here */} <Outlet /> </div> ) } }
Solution 2: Use Relative Paths with Wildcard Parent Route
If you prefer to keep the route definition inside the Home component:
- Update
App.jsto add a wildcard (*) to theHomeroute, allowing it to match all subpaths of/home:
<Routes> <Route path='/home/*' element={<Home/>}/> <Route path='/citylist' element={<CityList/>}/> </Routes>
- Update
Home/index.jsto use a relative path (news) instead of the absolute path:
import React from 'react' import {Routes, Route} from 'react-router-dom' import News from '../News' export default class Home extends React.Component { render(){ return( <div style={{backgroundColor:'skyblue',padding:10}}> home <Routes> {/* Use relative path instead of absolute */} <Route path='news' element={<News/>}></Route> </Routes> </div> ) } }
Either solution will fix the issue: when you navigate to http://localhost:3000/home/news, the News component will now render inside the Home component as expected.
内容的提问来源于stack exchange,提问作者bin
相关产品推荐
相关产品推荐

