renderToStaticNodeStream
将非交互式 React 树渲染到 Node.js 可读流。
¥renderToStaticNodeStream
renders a non-interactive React tree to a Node.js Readable Stream.
const stream = renderToStaticNodeStream(reactNode, options?)
参考
¥Reference
renderToStaticNodeStream(reactNode, options?)
在服务器上,调用 renderToStaticNodeStream
获取 Node.js 可读流。
¥On the server, call renderToStaticNodeStream
to get a Node.js Readable Stream.
import { renderToStaticNodeStream } from 'react-dom/server';
const stream = renderToStaticNodeStream(<Page />);
stream.pipe(response);
该流将生成 React 组件的非交互式 HTML 输出。
¥The stream will produce non-interactive HTML output of your React components.
参数
¥Parameters
-
reactNode
:要渲染为 HTML 的 React 节点。例如,像<Page />
这样的 JSX 元素。¥
reactNode
: A React node you want to render to HTML. For example, a JSX element like<Page />
. -
可选
options
:用于服务器渲染的对象。¥optional
options
: An object for server render.
返回
¥Returns
输出 HTML 字符串的 Node.js 可读流。生成的 HTML 无法在客户端上混合。
¥A Node.js Readable Stream that outputs an HTML string. The resulting HTML can’t be hydrated on the client.
注意事项
¥Caveats
-
renderToStaticNodeStream
输出不能水合。¥
renderToStaticNodeStream
output cannot be hydrated. -
在返回任何输出之前,此方法将等待所有 Suspense 边界 完成。
¥This method will wait for all Suspense boundaries to complete before returning any output.
-
从 React 18 开始,这个方法缓冲了它的所有输出,所以它实际上并没有提供任何流式传输的好处。
¥As of React 18, this method buffers all of its output, so it doesn’t actually provide any streaming benefits.
-
返回的流是以 utf-8 编码的字节流。如果你需要其他编码的流,请查看像 iconv-lite 这样的项目,它提供用于转码文本的转换流。
¥The returned stream is a byte stream encoded in utf-8. If you need a stream in another encoding, take a look at a project like iconv-lite, which provides transform streams for transcoding text.
用法
¥Usage
将 React 树作为静态 HTML 渲染到 Node.js 可读流
¥Rendering a React tree as static HTML to a Node.js Readable Stream
调用 renderToStaticNodeStream
以获取 Node.js 可读流,你可以将其通过管道传输到服务器响应:
¥Call renderToStaticNodeStream
to get a Node.js Readable Stream which you can pipe to your server response:
import { renderToStaticNodeStream } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const stream = renderToStaticNodeStream(<Page />);
stream.pipe(response);
});
该流将生成 React 组件的初始非交互式 HTML 输出。
¥The stream will produce the initial non-interactive HTML output of your React components.