为什么我不通过 Switch 进行路由?反应路由器 v4

Why am I not routing through the Switch? React Router v4

我正在使用 React Router 4,并且没有通过嵌套的 Switch 组件进行路由。这是我的路线:

const routes = (
  <div>
    <Switch>
      <Route exact path="/" >
        <Switch>
          <Route path="/test" component={Test} />
          <Route path="/other" component={Other} />
          <Route path="/about" component={About} />
        </Switch>
      </Route>
      <Route path="*" component={NotFound} />
    </Switch>
  </div>
);

我点击了根 / 路由,但是如果我尝试路由到任何其他嵌套路由 /about/other/test,我会转到我的错误页面。我认为这是因为我在 Route 上有 exact 和根 / 路由,但我不确定。我该如何解决这个问题?

如文档所述,

Switch renders the first child or that matches the location.

在你的情况下,外部开关必须在 2 之间进行选择,确切的 path="/" 和 *...所以它将始终与 NotFound 匹配,除非路径正好是 "/" 这就是为什么您应该从第 4 行中删除 exact 并将 <Route path="*" component={NotFound} /> 移到内部开关内。

对于你的情况,我会这样写:

const routes = (
    <Switch>
      <Route exact={true} path="/" component={Index} />
      <Route exact={true} path="/test" component={Test} />
      <Route exact={true}  path="/other" component={Other} />
      <Route exact={true} path="/about" component={About} />
      <Route path="*" component={NotFound} />
    </Switch>
);

您可以从我的工作示例中检查这些文件: https://github.com/sstawecki/polakete/blob/master/client/src/index.js https://github.com/sstawecki/polakete/blob/master/client/src/Routes.js