【问题标题】:Dynamic importing component in react router反应路由器中的动态导入组件
【发布时间】:2020-06-25 07:56:12
【问题描述】:

我想根据路由拆分捆绑包。因此尝试在 react-router 中进行动态导入,如下所示,但没有运气。也尝试了与 loadable 相同的方法,在 loadable 中,水合物启动时会闪烁。它删除了整个 dom 并再次添加。如何实现这一点?我不想将所有内容捆绑在一个文件中,同样我有 10 条不同的路线。

// With dynamic import
const routes = [
  {
    path: '/details/:name/:id',
    component: import(/* webpackChunkName: "details" */ '../components/details')
  }
];
// With Loadable
const Details = loadable(() => import('../components/details'), { ssr: true });
const routes = [
  {
    path: '/details/:name/:id',
    component: Details
  }
];

【问题讨论】:

  • 添加通过routes 映射的范围并创建react-router Routes。

标签: javascript reactjs react-redux react-router dynamic-import


【解决方案1】:

你可以使用render prop,而不是在Route 中使用component prop,它接受一个函数,因此允许你在内部实现一些逻辑

const routes = [
{
 path: '/details/:name/:id',
 render: () => condition ? import(/* webpackChunkName: "details" */ '../components/details') : import(/* webpackChunkName: "component2" */ '../components/component2')
}
];

【讨论】:

  • 它不工作,在 SSR 中出现错误。因为它会返回 Promise
猜你喜欢
  • 2016-02-24
  • 2022-12-20
  • 2021-02-05
  • 1970-01-01
  • 2021-06-27
  • 2019-08-30
  • 2020-07-30
  • 2017-08-07
  • 2023-03-30
相关资源
最近更新 更多