React Router 无法响应含参数的URL跳转,点击链接停留在Games页面问题求助
Hey there, let's figure out why your React Router isn't handling the parameterized URL correctly!
The root issue here is how React Router's Switch component works—it matches routes in the order you define them, and stops as soon as it finds the first matching one.
Right now, your /games route comes before /games/:id. When you click the link to /games/euromillions, the router first checks against /games and sees that it's a prefix match, so it renders the Games component and never gets to the Gamepage route you want.
Here are two straightforward fixes:
Fix 1: Reorder your routes to put more specific paths first
Move the /games/:id route above the /games route. Since it's a more specific path, it will match first when you visit a URL like /games/euromillions:
<Switch> <Route path="/homepage" component={Homepage} /> <Route path="/shops" component={Shops} /> <Route path="/products" component={Products} /> <Route path={`/games/:id`} render={(props) => <Gamepage {...props} />} /> <Route path="/games" component={Games} /> <Route path="/" component={Homepage} /> </Switch>
Fix 2: Add the exact prop to the /games route
The exact prop tells the router only to match the path exactly. This means /games will only render when the URL is exactly /games, and won't interfere with /games/:id:
<Switch> <Route path="/homepage" component={Homepage} /> <Route path="/shops" component={Shops} /> <Route path="/products" component={Products} /> <Route path="/games" exact component={Games} /> <Route path={`/games/:id`} render={(props) => <Gamepage {...props} />} /> <Route path="/" component={Homepage} /> </Switch>
As a bonus, you can also access the URL parameter in your Gamepage component to verify it's working:
const Gamepage = (props) => { return <h1>Welcome to the {props.match.params.id} game page!</h1>; };
Either fix should get your parameterized route working as expected.
内容的提问来源于stack exchange,提问作者Marshall

