服務端初始化Redux的必要性
- SSR為了解決首屏渲染時間和SEO的問題,那么首屏的內(nèi)容怎么辦?
- 服務端請求完首屏數(shù)據(jù)后,客戶端接管后是否又重新去請求首屏數(shù)據(jù)
- 為了解決以上問題所以服務端加載首屏數(shù)據(jù)并初始化到狀態(tài)樹非常必要
服務端加載首屏數(shù)據(jù)
// 1. 服務端拿到首屏數(shù)據(jù)放入狀態(tài)樹
app.get( "/*", async ( req, res ) => {
try {
let modules = [];
const context = {};
const store = createServerStore();
const { dispatch } = store;
const result = await fetchUserMsg('binyellow'); // 請求完首屏需要的數(shù)據(jù)
dispatch(initializeUserMsg(result.data)); // 將首屏數(shù)據(jù)傳入狀態(tài)樹
const jsx = (
<Provider store={store}>
<Loadable.Capture report={moduleName => modules.push(moduleName)}>
<StaticRouter context={ context } location={ req.url }>
<Layout />
</StaticRouter>
</Loadable.Capture>
</Provider>
);
const reactDom = renderToStaticMarkup( jsx );
let bundles = getBundles(stats, modules);
const state = store.getState();
res.writeHead( 200, { "Content-Type": "text/html" } );
res.end( htmlTemplate( reactDom, bundles, state ) );
} catch (error) {
throw error;
}
});
// 2.將JSON數(shù)據(jù)掛載到window的特殊key上
<script>
window.REDUX_DATA = ${ JSON.stringify( state ) }
window.env = 'server'
</script>
客戶端
// 1. 將window上的JSON數(shù)據(jù)初始化到Store中
const store = createClientStore( window.REDUX_DATA );
const jsx = (
<Provider store={store}>
<Router>
<Layout />
</Router>
</Provider>
);
要考慮的問題
- 服務端請求數(shù)據(jù)可能造成用戶等待時間,所以要簡化請求數(shù)據(jù)
- 客戶端要判斷develop狀態(tài)下(調(diào)試頁面),或者服務端請求出錯的情況下,去加載首屏數(shù)據(jù)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。