我是react-loadable库的新手。我想知道是否可以在服务器上使用React的renderToNodeStream而不是renderToString。
服务器index.js:
/* code... */
const appWithRouter = (
<Loadable.Capture report={moduleName => modules.push(moduleName)}>
<Provider store={store}>
<StaticRouter location={req.path} context={context}>
<div>{renderRoutes(Routes)}</div>
</StaticRouter>
</Provider>
</Loadable.Capture>
);
let bundles = getBundles(stats, modules);
const htmlStream = renderToNodeStream(appWithRouter);
res.status(200).write(renderHeader(htmlStream)); /* wrong ??? */
htmlStream.pipe(res, { end: false });
htmlStream.on('end', () => {
res.write( renderFooter(store, bundles) );
res.end();
});
});
Loadable.preloadAll().then(() => {
app.listen(PORT, () => console.log(`listening on port: ${PORT}`));
});
将render.js文件导入index.js:
export const renderHeader = (content) => {
console.log('content in renderHeader: ', content);
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/styles.css">
<title>Title</title>
</head>
<body>
<div id="app">${content}</div>`;
}
export const renderFooter = (store, bundles) => {
return `<script>
window.INITIAL_STATE = ${JSON.stringify(store.getState())}
</script>
<script src="/vendor.js"></script>
${bundles.map(bundle => {
return `<script src="/${bundle.file}"></script>`}).join('\\n')}
<script src="/app.js"></script>
</body>
</html>
`;
}
我还没有找到仅使用renderToNodeStream
renderToString
的任何示例或模式。是关闭还是关闭?我希望能够使用renderToNodeStream获得更快的响应。