【问题标题】:Implement nested async route fetching in React在 React 中实现嵌套的异步路由获取
【发布时间】:2017-02-17 13:52:25
【问题描述】:

是否可以使用System.import 实现嵌套的异步路由获取,这样一个应用程序只被分成几个合理的块,而不是许多小块?

背景

我正在我的 React 应用程序中实现捆绑拆分。 最初我实现了 bundle-loader(我无法在所有情况下都开始工作),然后使用 System.import,我发现它的行为更加可预测。

问题

代码拆分在逐个路由的基础上工作得很好,但是它会产生许多小包,并且额外的包和获取的开销是不必要且浪费的。

例如,我有这段代码,当您导航到他们的页面时,它会为仪表板、设置或图像加载包:

    <Provider store={store}>
        <Router history={browserHistory}>
            <Route path='/' component={Container}>
            <IndexRedirect to="Login" />
            <Route path='Registration' component={RegistrationContainer} />
            <Route path='Login' component={LoginContainer} />
            <Route path='Route1' >
                <IndexRedirect to="Dashboard" />
                <Route path='Settings' 
                        getComponent={ (loc, cb)=> {System.import('./components/Route1/Settings')
                                              .then(loadRoute(cb))
                                              .catch(errorLoading); }}/>
                <Route path='Dashboard' 
                        getComponent={ (loc, cb)=> {System.import('./components/Route1/Dashboard')
                                              .then(loadRoute(cb))
                                              .catch(errorLoading); }}
                    />
                <Route path='Images' 
                        getComponent={ (loc, cb)=> {System.import('./components/Route1/Images')
                                              .then(loadRoute(cb))
                                              .catch(errorLoading); }}
                    />
        </Router>
    </Provider>

第一次导航到 Route1 路径时,是否可以为所有三个加载捆绑包?

非常感谢

【问题讨论】:

    标签: reactjs webpack react-router code-splitting


    【解决方案1】:

    我已经尝试并设法找到一种解决方案,可以将任何给定数量的子路由的 get 请求数量减少到 2。

    我得到这个结果的方法是在Route1中引入一个索引组件

    <Route path='Patient' getComponent={ (loc, cb)=> {System.import('./components/Route1Index')
                .then(loadRoute(cb))
                .catch(errorLoading); }}>
    

    然后我为所有子路由创建了索引组件,如下所示:

    import React from 'react';
    
    // Child route components
      import Settings from './Settings';
      import Dashboard from './Dashboard';
      import Images from './Images';
    
    export default (props) =>(
      <div>
            {props.children}
      </div>
    )
    

    我还在 Webpack 中设置了minChunks:2 CommonsChunkPlugin

    现在,当我导航到 Route1 的任何子路由时,只加载了 2 个包:Route1Index 包和包含所有导入的包

    【讨论】:

    • 你是如何为异步加载的组件设置路径的?我的意思是&lt;Route path='Dashboard' ...
    • 嗨,Oleh,我不太清楚你这个问题是什么意思。路线路径显示在我的答案的第一行。导航到路径后,组件将被异步获取,只要该组件位于单独的 bundle.js 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多