【问题标题】:Custom components not being matched using react-router使用 react-router 不匹配的自定义组件
【发布时间】:2021-06-23 19:41:18
【问题描述】:

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

我有一个 Application Routes 组件,它有 3 个子组件作为组件

  • AuthenticatedRoutes
  • PublicRoutes
  • Error404Route

每个组件呈现不同的路由/组件,但只有第一个组件 (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。

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

谢谢!

【问题讨论】:

  • 拥有这么多开关有什么意义?我认为删除所有内部开关可以解决您的问题

标签: javascript reactjs typescript react-router react-router-dom


【解决方案1】:

试试这样:

应用程序路由

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}/>,
];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2021-03-10
    • 2020-08-20
    • 2019-01-18
    • 2020-03-27
    相关资源
    最近更新 更多