React Router中静态路由与动态路由的匹配顺序问题及解决方法咨询
Ah, I see the issue here! The problem lies in how you've nested your <Layout> component inside the <Switch>. Let me break this down for you:
Why Your Current Setup Fails
The <Switch> component in React Router is designed to render only the first matching direct child <Route> or <Redirect>. In your code, the <Switch> has just one direct child: <Layout>, which contains all three routes. This means the <Switch> doesn't handle the route matching logic at all—instead, all three <Route> components inside <Layout> are rendered whenever their paths match.
When you visit /videos, both <Route exact path="/videos"> and <Route path="/:url"> end up matching:
- The exact route matches
/videosperfectly - The dynamic route
/\:urltreats"videos"as theurlparameter and also matches
Since both routes render their components, the dynamic route's <Post> ends up overriding or appearing alongside <Videos>, which is why you're seeing the issue.
The Fix: Restructure Your Components
Move the <Layout> outside the <Switch> so that the <Switch> directly contains your <Route> components. This way, the <Switch> can properly prioritize matching routes in order:
<Router onUpdate={() => window.scrollTo(0,0)} history={history}> <Layout> <Switch> <Route exact path="/" render={() => <Home />} /> <Route exact path="/videos" render={() => <Videos />} /> <Route path="/:url" render={() => <Post />} /> </Switch> </Layout> </Router>
How This Works
Now the <Switch> is the direct parent of your routes, so it will:
- Check if the current path matches
/exactly (renders<Home>if true) - If not, check if it matches
/videosexactly (renders<Videos>if true) - If neither of the above match, it will fall back to the dynamic
/\:urlroute and render<Post>
Additional Notes
- Make sure you're using React Router v4 or later (the
<Switch>component was introduced in v4) - The
exactprop on your static routes is still important here—it ensures/doesn't match every route, and/videosdoesn't match paths like/videos/123(if you ever add sub-routes for videos)
This setup will guarantee your static routes take precedence over the dynamic one, just like you expected!
内容的提问来源于stack exchange,提问作者Wally Kolcz

