2016-07-22 69 views
1

我想異步地根據不同的用戶類型能夠加載反應的組分。例如,當用戶A圍繞應用程序導航時,他們的一組組件通過異步加載。然後,當用戶B使用應用程序時,他們收到了另一組通過異步加載的組件。如何基於不同的服務器端狀態異步加載React組件?

在我使用的陣營路由器和終極版的時刻。我也用的WebPack創建組件塊,其負載異步這樣的:

<Route 
    path="/" 
    getComponent={(location, callback) => { 
    require.ensure([], (require) => { 
     callback(null, require('./app/App.jsx').default); 
    }, 'App'); 
    }} 
> 

但是當我嘗試擴大這種動態加載組件這是行不通的。我創建對象的數組它包含了所有我想要加載組件...

{ 
    components: [ 
    { 
     id: 0, 
     name: 'Dashboard', 
     src: './dashboard/Dashboard.jsx', 
     indexRoute: true, 
     path: '/', 
    }, 
    { 
     id: 1, 
     name: 'Quote', 
     src: './quote/Quote.jsx', 
     indexRoute: false, 
     path: '/quote', 
    }, 
    ], 
} 

然後我用地圖來創建這些組件的每一個路線...

const routes = components.map((component) => { 

    if (component.indexRoute) { 
    return (
     <IndexRoute 
     getComponent={(location, callback) => { 
      require.ensure([], (require) => { 
      callback(null, require(component.src).default); 
      }, component.name); 
     }} 
     key={component.id} 
     /> 
    ); 
    } 

    return (
    <Route 
     path={component.path} 
     getComponent={(location, callback) => { 
     require.ensure([], (require) => { 
      callback(null, require(component.src).default); 
     }, component.name); 
     }} 
     key={component.id} 
    /> 
); 
}); 

但是,當我插入我創建路由到主路...

<Route 
    path="/" 
    getComponent={(location, callback) => { 
    require.ensure([], (require) => { 
     callback(null, require('./app/App.jsx').default); 
    }, 'App'); 
    }} 
> 
    {routes} 
</Route> 

我得到以下錯誤:

Uncaught TypeError: __webpack_require__(...).ensure is not a function 

和警告:

require function is used in a way in which dependencies cannot be statically extracted 

我相信這是因爲的WebPack需要知道什麼豆腐塊它在構建時編譯?這是問題,有沒有辦法解決這個問題?甚至更好的解決方案?

感謝

+0

看看https://webpack.github.io/docs/code-splitting.html我認爲require.ensure()只同步工作,您可能需要使用AMD。 – r0dney

+0

感謝info @ r0dney :) –

回答

0

任何人誰在後一階段遇到這個問題,我設法與所有的異步組件我的應用程序可能會加載創建一個對象來解決這個問題。每個組件路由定義了它就像這樣定義require.ensure功能...

const asyncComponents = [ 
    { 
    id: 0, 
    name: 'Dashboard', 
    require: (location, callback) => { 
     require.ensure([], (require) => { 
     callback(null, require('./dashboard/Dashboard.jsx').default); 
     }, 'Dashboard'); 
    }, 
    }, 
]; 

export default asyncComponents; 

這樣做,這樣將不可避免地面臨在某個時刻結垢問題,你必須保持所有組件的單獨列表。它現在雖然工作。