2017-02-24 63 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個月的應用程序,我目前正在努力。迄今爲止沒有任何限制 –