我是 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}`));
});
导入 index.js 的 render.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 来获得更快的响应。