2017-02-24 35 views
0

我的代码拆分问题是,如果模块很大,第一次用户会看到一个空白屏幕和延迟。动态路由代码拆分检查模块是否加载

function errorLoading(err) { 
     console.error('Dynamic page loading failed', err); 
    } 

    function loadRoute(cb) { 
     return (module) => cb(null, module.default); // I can't find any flag here 
    } 

    const routes = { 
     component: App, 
     childRoutes: [ 
     { 
      path: '/', 
      getComponent(location, cb) { 
      System.import('pages/Home') 
       .then(loadRoute(cb)) 
       .catch(errorLoading); 
      } 
     } 
     ] 
    }; 

export default() => <Router history={browserHistory} routes={routes} />; 

下面是使用动态路由代码分裂基地工作的例子。

https://github.com/ModusCreateOrg/react-dynamic-route-loading-es6/blob/master/client/pages/routes.js

我如何检查是否模块被加载与否?我必须加载一个加载指示器。

+0

一般来说对于这一点,我的建议是不是“检查它被加载“,它是”如果它没有在X毫秒渲染,显示一个微调,这是什么适合你吗? – loganfsmyth

+0

@loganfsmyth没有标志来检查,这是我的问题,你的建议是使用setinterval检查? –

回答

0

为了使这个工作,你需要动态加载组件代码而不是getComponent挂钩。

在我的应用程序中有一个名为LazyComponent的组件,它在需要时动态加载包。此外,它可以让你同时你的大包是加载显示的东西:

class LazyComponent extends React.Component { 
    constructor() { 
    this.state = {Component: null}; 
    super(); 
    } 

    componentDidMount() { 
    const pageName = this.props.location.params.page; 
    System.import(`pages/${pageName}.js`).then(
     Component => this.setState({Component}), 
     error => this.setState({error}) 
    ) 
    } 

    render() { 
    const { Component, error } = this.state; 

    // render error message when bundle has failed to load 
    if(error) { 
     return <div>{error.message}</dib> 
    } 

    // render loader while component is not ready 
    if(!Component) { 
     return <div>Loading...</div> 
    } 

    // render the component itself 
    return <Component {...this.props} /> 

    } 
} 

然后你就可以把这个组件到你的路由定义

const routes = { 
    component: App, 
    childRoutes: [ 
    { 
     path: '/', 
     component: LazyComponent 
    } 
    ] 
}; 
+0

哇哇大叫!不知道我可以用System导入另一个组件,但是这个方法有没有什么限制? –

+0

我一直在使用这个在过去2个月的应用程序,我目前正在努力。迄今为止没有任何限制 –