ngOnInit 生命周期钩子行为与路由模块



我在应用的根路由模块中使用以下路由:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'home',
        component: HomeDetailsComponent,
      },
      {
        path: 'home',
        component: HomeDetailsComponent,
        children: [
          {
            path: 'room/:id', 
            component: RoomDetailsComponent,
          },
        ]
      },
      {
        path: 'sectorNumber',
        component: SectorNumberComponent
      },
      {
        path: '**',
        redirectTo: 'home',
      },
    ]
  }
];

现在,在HomeDetailsComponent中,我正在使用OnInit生命周期钩子来调用http get方法,并在此基础上进行一些事件处理。但是,我注意到使用这种路由,我的HomeDetailsComponent被初始化了两次。一次是导航到'http://localhost:3000/#/curriculum/',第二次是导航到'http://localhost:3000/#/curriculum/chapter/1'路线。谁能告诉我为什么会这样?

因为组件不会重用于不同的路由。将销毁您导航离开的路径中的组件,并创建您导航到的组件。仅当从路由和到路由相同但参数值 ( :id) 更改时,这才不同。

最新更新