索引路由旁边的反应路由器 v4 通配符

React router v4 wildcard next to index route

假设我们有这个设置

const Parent = () => (
  <Switch>
    <Route path="/data" component={Child}
  </Switch>
)

const Child = () => (
  <Switch>
    <Route exact path="/" component={SomethingList} />
    <Route path="/:id" component={ShowSomething} />
  </Switch>
);

当我渲染父级时,我希望 someUrl/data 渲染 SomethingListsomeUrl/5 渲染 ShowSomething。实际发生的是两者都呈现 ShowSomething.

如何使用 react-router v4 获得我期望的行为?

那是因为 /:id 并不意味着它必须是整数值。它可以是任何形式:/some-path - id 等于 some-path。这就是您出现这种行为的原因。

在您的上下文中,呈现 SomethingList 的唯一方法是使用 / 路由。没有其他匹配。我会这样做:

const Parent = () => (
  <Switch>
    <Route path="/data" component={Child}
  </Switch>
)

const Child = () => (
  <Switch>
    <Route exact path="/data" component={SomethingList} />
    <Route path="/data/:id" component={ShowSomething} />
  </Switch>
);

我猜你认为你可以在你的子组件中声明相对路径,这(我认为)对于 RR4 是不可能的。