React路由异常求助:有效路由同时显示NotFound组件
React Router v5 路由匹配问题:有效路由同时显示NotFound组件
问题说明
使用react-router-dom ^5.2.0时,访问有效路由(如localhost:3000/faq),页面会同时展示对应路由内容和自定义NotFound组件;仅希望访问无效路由时才显示NotFound。
问题原因
React Router v5中,<Switch>组件的作用是只渲染第一个匹配当前路径的路由,但你的BuildRoutes组件内部用<>(React.Fragment)包裹所有路由,而非<Switch>。这导致所有匹配当前路径的路由都会被渲染——包括path="*"的NotFound路由(它匹配所有路径),或者你后来添加的无path的<Route component={NotFound}>(默认匹配所有路径),因此有效路由下也会渲染NotFound。
解决方案
修改BuildRoutes组件,用<Switch>替代<>包裹所有路由,确保只有第一个匹配的路由被渲染,并将NotFound路由放在所有路由的最后。
修改后的BuildRoutes组件代码
const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={(props) => rest.isAuth === true ? ( <Component {...props} {...rest} /> ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location }, }} /> ) } /> ) export const BuildRoutes = ({ isMobile, isAuth, auth }) => { const location = useLocation() useEffect(() => { const queryParams = QueryString.parse(location.search) setFeatureFlag(queryParams) }, [location]) return ( <Switch> {/* 替换原有的<>为Switch */} {routes.map( ({ path, component: Component, is_private, is_mother }, key) => !is_private ? ( <Route exact={is_mother ? false : true} path={path} key={key} render={(props) => ( <Component {...props} isMobile={isMobile} isAuth={isAuth} auth={auth} /> )} /> ) : ( <PrivateRoute isAuth={isAuth} isMobile={isMobile} auth={auth} exact={is_mother ? false : true} path={path} key={key} component={Component} /> ) )} <Route exact path="/brand/:brandName" render={(props) => { const { brandName } = props.match.params if (bikeBrands.includes(brandName)) { return <Redirect to={`/brand/${brandName}-rental`} /> } return <BrandLandingPage brandName={brandName} /> }} /> {/* 最后放置NotFound路由,仅当前面无匹配项时渲染 */} <Route component={NotFound} /> </Switch> ) }
额外注意事项
- 移除routes数组中的NotFound路由配置,避免重复渲染;
- 所有路由必须被
<Switch>包裹,React Router会按顺序匹配,找到第一个匹配路由后停止,不会渲染后续路由; - 末尾的
<Route component={NotFound}>无需设置path,它会自动在前面所有路由都不匹配时触发。
内容的提问来源于stack exchange,提问作者Bahubali Ak
相关产品推荐
相关产品推荐

