React Router 4子路由问题求助:多路由拆分与页面跳转失败
Hey there! Let's break down why your navigation isn't working after fetching data when using nested sub-app routers, and fix it step by step.
The Core Problem: Conflicting Router Contexts
From what you described, it sounds like each sub-app is probably wrapping its own routes with a <BrowserRouter>—this creates a separate, isolated routing context from your main app's router. When you call navigation functions (like navigate) from a sub-app's local router, it won't update the main browser history or address bar, making it seem like the "page isn't changing."
Fixes to Implement
1. Use a Single Root BrowserRouter
Your main app should be the only one responsible for providing the root routing context. Remove any <BrowserRouter> components from your sub-apps entirely.
Example Main App Router Structure:
// Main Routes.js import { BrowserRouter, Routes, Route } from 'react-router-dom'; import SubAppA from './subapps/SubAppA'; import SubAppB from './subapps/SubAppB'; function AppRouter() { return ( <BrowserRouter> <Routes> // Use wildcard (*) to pass all sub-routes to the sub-app <Route path="/subapp-a/*" element={<SubAppA />} /> <Route path="/subapp-b/*" element={<SubAppB />} /> </Routes> </BrowserRouter> ); }
2. Nest Sub-App Routes Without a New Router
In each sub-app, use <Routes> and <Route> directly (no BrowserRouter!) to handle its internal routes. The wildcard path from the main router will ensure all sub-app routes are matched correctly.
Example Sub-App with Navigation After Fetch:
// SubAppA.js import { Routes, Route, useNavigate } from 'react-router-dom'; import SubAppHome from './SubAppHome'; import SubAppDetail from './SubAppDetail'; function SubAppA() { const navigate = useNavigate(); // Pulls from the main router's context const fetchDataAndNavigate = async () => { try { // Fetch your data here const response = await fetch('/api/subapp-data'); const data = await response.json(); // Navigate to sub-app's detail page AFTER fetch completes navigate('/subapp-a/detail', { state: { data } }); } catch (error) { console.error('Fetch failed:', error); } }; return ( <div className="sub-app-a"> <button onClick={fetchDataAndNavigate}>Load Data & Go to Detail</button> <Routes> <Route path="/" element={<SubAppHome />} /> <Route path="/detail" element={<SubAppDetail />} /> </Routes> </div> ); }
3. Verify Async Navigation Logic
Double-check that your navigation call happens after the fetch promise resolves. If you call navigate before awaiting the fetch, it might execute before your data is ready, or in some cases, be blocked by the async flow.
Key Takeaways
- Only one
<BrowserRouter>should exist in your entire app (at the root level). - Sub-apps inherit the routing context from the main router, so
useNavigate,useLocation, etc., will work as expected. - Use wildcard paths (
/*) in the main router to pass sub-route control to each sub-app.
内容的提问来源于stack exchange,提问作者jmrosdev

