React路由使用Redirect时出现循环问题的解决方案咨询
Let’s start by breaking down why you’re stuck in that infinite redirect loop: your checkBrowser route doesn’t have a path prop, which means every single URL will match this route first. When you return <Redirect to="/login" /> for supported browsers, the app jumps to /login—but then the checkBrowser route matches again, triggers another redirect, and the cycle repeats forever.
Here’s how to fix this properly:
1. Refactor the Browser Detection Component
Instead of forcing a redirect when the browser is supported, let the normal routing flow take over. Modify your checkBrowser component to only render the error page for unsupported browsers, and return null otherwise:
class CheckBrowser extends React.Component { detectIE() { const ua = window.navigator.userAgent; const msie = ua.indexOf('MSIE '); if (msie > 0) { return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); } return false; } render() { if (this.detectIE()) { return ( <FullPageError title={''} image={<BntIconWrapper icon={<SvgPageErrorGeneric />} defaultColor={true} />} explanation={''} userOptions={''} /> ); } // For supported browsers: return null so Switch moves to the next matching route return null; } }
2. Keep Your Route Structure (With a Small Adjustment)
Your existing Switch setup stays mostly the same—just keep the CheckBrowser route at the top. When a supported browser hits any URL, CheckBrowser returns null, and the Switch will automatically find the next matching route below it:
<Switch> <Route component={CheckBrowser} /> <Route exact path="/login" component={checkLogin} /> <Route exact path="/signin-oidc" component={checkSignInOidc} /> <Route path="/error-page" component={ErrorPageContainer} /> <Route path="/authorizeExternal" component={AuthorizeExternal} /> <Route path="/" component={checkDarklyProjects} /> <Route path="**" component={NotFound} /> </Switch>
3. Add Default Redirect (If Needed)
If you want users landing on the root path (/) to be sent to /login, add that redirect as a separate route after your other specific routes:
<Switch> <Route component={CheckBrowser} /> <Route exact path="/login" component={checkLogin} /> <Route exact path="/signin-oidc" component={checkSignInOidc} /> <Route path="/error-page" component={ErrorPageContainer} /> <Route path="/authorizeExternal" component={AuthorizeExternal} /> <Route path="/dashboard" component={checkDarklyProjects} /> {/* Update to your actual app route */} <Route path="/" render={() => <Redirect to="/login" />} /> <Route path="**" component={NotFound} /> </Switch>
This way, the redirect only fires when no other specific routes match, and it won’t trigger the CheckBrowser loop because /login will match its own dedicated route.
内容的提问来源于stack exchange,提问作者user6408649

