react-pdf:异步使用 PDFDownloadLink 而不会阻塞应用程序的其余部分

react-pdf: use PDFDownloadLink asynchronously without blocking the rest of the application

我正在使用 react-pdf 包中的 PDFDownloadLink 在我的应用程序中即时生成 PDF,并允许用户根据传递给生成组件的数据下载报告PDF 文档。但是这个PDF有400多页需要渲染,这个操作阻塞了主线程几秒。有什么方法可以使此操作异步,以便在生成 PDF 时应用程序的其余部分将继续运行?此外,我希望能够缓存结果,因为传递给组件的数据可以来自大约 8 个不同的数据数组,这些数据变化不大,所以我宁愿不必在这些数组之间切换如果给定数组的 PDF 之前已经生成过一次,则重新渲染 PDF ...我猜 blob 数据需要存储在某个地方,也许是 localStorage?

import { Page, Text, View, Document, StyleSheet, PDFDownloadLink } from '@react-pdf/renderer'
const App = () => {
    const condition = "firstCondition";
    const filteredRowData = rowData.filter(a => a.condition = condition);
    return (
            <PDFDownloadLink
                document={<PDF_REPORT_Document rowData={filteredRowData} />}
                fileName={"PDF_REPORT.pdf"}
                style={{color:'white'}}
                >{({ blob, url, loading, error }) =>
                    loading ? "Report loading..." : "Report ready to download"
                }</PDFDownloadLink>
    );
}

const PDF_REPORT_Document = (props) => {
    const { rowData } = props;
    const styles = StyleSheet.create({
        page: {
          flexDirection: 'column',
          backgroundColor: '#E4E4E4'
        },
        section: {
          margin: 10,
          padding: 10,
          flexGrow: 1
        }
    });

    return(
        <Document>
        {rowData.map((row,index) => 
            <Page size="A4" style={styles.page} key={index}>
                <View style={styles.section}>
                    <Text>Name: {row.FULLNAME}</Text>
                </View>
            </Page>
        )}
        </Document>
    );
}

我终于在 issue on github 中找到了解决这个问题的答案:

Is your feature request related to a problem? Please describe. It is an improvement. At the moment, if you use 'PDFDownloadLink' the PDF is being generated as the component loads.

Describe the solution you'd like It is not mandatory, but having multiple heavy PDFs ready to be downloaded wouldn't be the best approach since not every user will need it.

Describe alternatives you've considered I've used pdf() function to generate the blob and file-saver lib to download it:

import { saveAs } from 'file-saver';
import { pdf } from '@react-pdf/renderer';
import PdfDocument from '../PdfDocument';

const generatePdfDocument = async (documentData,fileName) => {
        const blob = await pdf((
            <PdfDocument
                title='My PDF'
                pdfDocumentData={documentData}
            />
        )).toBlob();
        saveAs(blob, fileName);
};

export default generatePdfDocument;