【问题标题】:NotFound route always showing with static routes - [React Router 4]NotFound 路由总是显示静态路由 - [React Router 4]
【发布时间】:2017-12-08 01:32:33
【问题描述】:

如何使用React Router 4 和静态路由定义 notFound 组件?

我使用react-router-reduxnext版本。所以,在我的客户中:

export default function appRoutes(history) {
  return (
    <ConnectedRouter history={history}>
      <div>
        {routes.map((route, key) => (
          <Route key={key} {...route} />
        ))}
      </div>
    </ConnectedRouter>
  );
}

路线是:

export const routes = [
  {
    path: '/',
    component: App
  },
  {
    path: '/:lang/chat',
    component: Chat
  },
  {
    path: '/:lang',
    component: Listing
  },
  ...
  {
    path: '*',
    component: NotFound,
    status: 404
  },
];

使用这种方法,找不到的组件总是与匹配的路由一起显示。

我已经读过,我必须使用 Switch,而不是使用 div 包装上述 appRoutes 方法。但是使用这种方法,路由永远不会匹配。

编辑

我想同时显示,例如App组件和Listing组件,但NotFound也在显示。

那么,我做错了什么?

【问题讨论】:

    标签: reactjs react-router react-router-redux react-router-v4


    【解决方案1】:

    React 路由器 V4 显示所有匹配的路由。如果您只想显示一个使用 Switch 组件。

    【讨论】:

    • 但是如果我有“/”路由,它显示“App”组件,我有标题,然后我有列表组件,“/:lang”,在标题下方?你说的没错,用 Switch 只会渲染第一个匹配组件,也就是 App。
    • 我不确定您指的是什么,但如果我理解正确,请使用确切属性。
    • 如果我想在url为route/en时渲染App组件和Listing组件,我必须使用确切的属性吗?那么组件notFound 呢?不会显示?我必须在我定义的所有静态路由器组件中使用精确吗?谢谢
    【解决方案2】:

    我找到了适合我的解决方案。我已经从静态路由中删除了App 组件并放置在之前,然后我使用Switch 仅渲染一个路由。

    export default function appRoutes(history) {
      return (
        <ConnectedRouter history={history}>
          <div>
            <Route path='/' component={App} />
            <Switch>
              {routes.map((route, key) => (
                <Route key={key} {...route} />
              ))}
            </Switch>
          </div>
        </ConnectedRouter>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-30
      • 2020-12-26
      • 2018-12-25
      • 1970-01-01
      • 2021-10-04
      • 2023-02-26
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      相关资源
      最近更新 更多