我尝试使用React18中的renderToPipeableStream函数。它很管用,但我管不好。
我想这是我代码的重要部分。html是html的字符串数组。我把字符串拆分在中间,我想把react代码放在中间。
server.get("/", (req: any, res: any) => {
res.write(html[0] + '<div id="root">')
const stream = ReactDomServer.renderToPipeableStream(
<App />
).pipe(res, { end: false })
stream.on("end", () => {
res.write('</dev>' + html[1])
res.end()
})
})
问题是CCD_ 1不发射。但我想要这个,因为没有是html代码不完整。浏览器忽略了这一点,但这并不好。
这对我有效:
const stream = renderToPipeableStream(jsx, {
onAllReady() {
res.end(`</div></body></html>`);
},
});
stream.pipe(res, { end: false });
res.flush();
https://reactjs.org/docs/react-dom-server.html#rendertopipeablestream
我用以下代码解决了这个问题
const app = renderToPipeableStream(<App />);
res.type('html');
res.write(getDocumentHead(req, res)); //Custom function to construct header html
app.pipe(res, {end: false});
res.write(getDocumentEnd(req, res)); //Custom function to construct scripts
res.end();