首页 > 解决方案 > 未使用 react-router 匹配的自定义组件

问题描述

我试图将关注点与我的路线分开,让我的反应代码更有条理。我目前正在使用react-router-domv5。

我有一个Application Routes包含 3 个子组件的组件

每个组件呈现不同的路由/组件,但只有第一个组件 ( AuthenticatedRoutes) 被匹配。

申请途径

export const ApplicationRoutes = () => (
  <Switch>
    <AuthenticatedRoutes />
    <PublicRoutes />
    <Error404Route />
  </Switch>
);

认证路由

export const AuthenticatedRoutes = () => (
  <Switch>
    <Route exact path='/dashboard'>
      <Dashboard />
    </Route>
    <Route exact path='/profile'>
      <Profile />
    </Route>
  </Switch>
);

公共路线

export const PublicRoutes = () => (
  <Switch>
    <Route exact path='/about'>
      <About />
    </Route>
    <Route exact path='/'>
      <Home />
    </Route>
  </Switch>
);

错误路线

export const Error404Route = () => (
  <Switch>
    <Route>
      <Error404 />
    </Route>
  </Switch>
);

所以,我是说只有AuthenticatedRoutes(/dashboard/profile) 被匹配,公共路由error404路由不是。

我认为如果您使用 Switch 路由将尝试匹配位置路径名,如果不匹配,则会显示 Error404Route。

我错过了什么吗?(当然我是)

谢谢!

标签: javascriptreactjstypescriptreact-routerreact-router-dom

解决方案


试试这样:

申请途径

import AuthenticatedRoutes from './AuthenticatedRoutes'
import PublicRoutes from './PublicRoutes'
import Error404Route from './Error404Route'

export const ApplicationRoutes = () => (
  <Switch>
    {AuthenticatedRoutes}
    {PublicRoutes}
    {Error404Route}
  </Switch>
);

认证路由

import Dashboard from './Dashboard'
import Profile from './Profile'

export const AuthenticatedRoutes = [
  <Route exact path='/dashboard' component={Dashboard}/>,
  <Route exact path='/profile' component={Profile}>,
];

公共路线

import Home from './Home'
import About from './About'

export const PublicRoutes = [
  <Route exact path='/' component={Home}/>,
  <Route exact path='/about' component={About}>,
];

错误路线

import Error404 from './Error404'

export const Error404Route = [
  <Route exact path='/' component={Error404}/>,
];

推荐阅读