React Router结合TransitionGroup使用Redirect时出现重复路由警告问题
I've run into this exact issue before when combining React Router transitions with redirects—here's how I fixed it:
The Root Cause
When you enter an invalid path (like /abc), your Redirect component tries to send you to /, but if the transition animation is still in progress (or if the route state isn't updating correctly), it might end up attempting that redirect even after you're already on /, triggering the warning.
Solution 1: Guard Redirect with Current Path Check
The simplest fix is to only render the Redirect if the current path isn't already your target route. Use the useLocation hook to validate this:
import { useLocation, Redirect, Route, Switch } from 'react-router-dom'; import { TransitionGroup, CSSTransition } from 'react-transition-group'; function App() { const location = useLocation(); return ( <TransitionGroup> <CSSTransition key={location.key} timeout={300} classNames="fade"> <Switch location={location}> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> {/* Only redirect if we're not already on the root path */} {location.pathname !== "/" && <Redirect to="/" />} </Switch> </CSSTransition> </TransitionGroup> ); }
Make sure you pass the location prop to the inner Switch—this ensures the Transition Group uses the correct route state during animations, preventing mismatches that cause repeated redirects.
Solution 2: Use History.replace Instead of Redirect Component
If you still see issues, try handling the redirect programmatically with history.replace instead of the Redirect component. This gives you tighter control over when the redirect fires:
import { useHistory, useLocation, Route, Switch } from 'react-router-dom'; import { TransitionGroup, CSSTransition } from 'react-transition-group'; function NotFoundRedirect() { const history = useHistory(); const location = useLocation(); useEffect(() => { // Only redirect if we're not already on the root if (location.pathname !== "/") { history.replace("/"); } }, [location.pathname, history]); return null; } function App() { const location = useLocation(); return ( <TransitionGroup> <CSSTransition key={location.key} timeout={300} classNames="fade"> <Switch location={location}> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route component={NotFoundRedirect} /> </Switch> </CSSTransition> </TransitionGroup> ); }
Key Notes
- Always wrap your
Switchinside theCSSTransitionand pass thelocationprop to theSwitch—this keeps the transition state synced with the current route. - Avoid unguarded
Redirectcomponents at the end of yourSwitch—they'll fire every time the route updates, even if you're already on the target path.
内容的提问来源于stack exchange,提问作者Steve R

