簡體   English   中英

使用自定義 html 反應 SSR Suspense

[英]React SSR Suspense with custom html

我開始在我的 react 應用程序中使用 Suspense,然后將其轉換為 SSR,但是在閱讀文檔時: https ://reactjs.org/docs/react-dom-server.html#rendertopipeablestream

在我們使用將 div#root 替換為 renderToString() 之前,我看不到任何地方如何使用自定義 HTML並且您可以添加文檔的標題和元標記,現在,使用該函數我只看到如何返回<App />中帶有renderToPipeableStream函數的 html 字符串:

const stream = renderToPipeableStream(
    <StaticRouter location={req.url}>
        <App
            data={json}
            pathLang={checkLanguage(lang) ? lang : ''}
            statusCode={status}
            cookiesAccepted={accepted}
        />
    </StaticRouter>,
    {
        onShellReady() {
            res.setHeader('Content-type', 'text/html');
            stream.pipe(res);
        },
    }
);

有什么方法可以攔截構造的 html 以便將其放入我的index.html中?

我剛剛通過按照https://stackoverflow.com/a/70900625/6732429創建自己的WritableStream解決了這個問題:

// HtmlWritable.js
import {Writable} from 'stream';

class HtmlWritable extends Writable {
    chunks = [];
    html = '';

    getHtml() {
        return this.html;
    }

    _write(chunk, encoding, callback) {
        this.chunks.push(chunk);
        callback();
    }

    _final(callback) {
        this.html = Buffer.concat(this.chunks).toString();
        callback();
    }
}

export default HtmlWritable;

並像這樣實現它:

// server.jsx
import HtmlWritable from './HtmlWritable';
[...]
const writable = new HtmlWritable();
const stream = renderToPipeableStream(
    <StaticRouter location={req.url}>
        <App
            data={json}
            pathLang={checkLanguage(lang) ? lang : ''}
            statusCode={status}
            cookiesAccepted={accepted}
        />
    </StaticRouter>,
    {
        onShellReady() {
            res.setHeader('Content-type', 'text/html');
            stream.pipe(writable);
        },
    }
);

writable.on('finish', () => {
    const html = writable.getHtml();
    data = data.replace('<div id="root"></div>', `<div id="root">${html}</div>`);
    resolve({data, status});
});
[...]

其中dataindex.html的返回fs.readFile

那是我的解決方案,如果您解決了不同的問題,請分享!

非常感謝並隨時發表評論,我想知道您的意見

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM