react-router:嵌套路由组件在父路由组件之前安装?

react-router: Nested route component mounts before parent route component?

我有一个这样的嵌套路由:

<Route path="modules" component={Modules}>
  <Route path=":moduleId" component={Module}/>
</Route>

我注意到 ModuleModules 安装之前安装。这是嵌套路由的预期功能吗? 我问是因为我在 Modules 中收集了一些数据,需要解决这些数据才能 Module 按预期呈现。

如果我看到 Modules 甚至在安装之前就已经呈现,这怎么可能?

这不是 react-router 特有的。在 React Component life-cycle:

  • Children 在 parents 之前安装。 componentWillMount 运行 child-first.

  • Parents 在 children 之前被卸载。 componentWillUnmount 运行 parent-first.

这样想:如果您正在构建某个东西,首先您将较小的部分逐步连接到较大的部分,直到您拥有完整的东西。如果您要拆解它,请先拆下较大的部件,然后再拆解每个部件,直到您回到组件。

您看到的是因为 react-router 没有 真正地 使用 React 生命周期过程来渲染它的子进程。

相反,react-router 单独呈现每个 <Route> 的组件,然后将它们合并在一起。这就是为什么必须在具有子路由的组件路由中包含 this.props.children 的原因。您可以在 <RouterContext> 的渲染函数中看到负责此的代码。

本质上它所做的是获取最嵌套的路由组件并渲染它。然后,它获取下一个最嵌套的组件,并使用先前渲染的组件作为其 children 属性来渲染它。这将继续下去,直到到达根路由组件。

给定路线:

<Route path="/" component={App}>
  <Route path="inbox" component={Inbox}>
    <Route path="messages/:id" component={Message} />
  </Route>
</Route>

当您访问 /inbox/messages/12 时,react-router 将执行以下操作:

  1. 渲染 <Message routeParams={{ id: 12 }} /> 并将结果存储为 element
  2. 渲染 <Inbox children={element} /> 并将结果存储为 element
  3. 渲染 <App children={element} /> 和 return 结果。