You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何从Firebase数据库获取查询的文档数据

提取Firebase文档纯数据并适配PDF遍历需求

1. 提取文档实际数据

你当前存储的是Firebase的DocumentSnapshot对象数组,包含了快照状态、文档引用等元数据。要获取文档的实际内容,只需调用每个快照的data()方法,还可以按需保留文档ID:

const [Annotations, setAnnotations] = useState([]); // 初始值设为空数组更合理
useEffect(() => {
    const q = query(
      collection(db, "notifications"),
      orderBy("createdAt", "desc")
    );
    onSnapshot(q, (test) => {
      // 映射提取纯数据,可选保留文档ID
      const pureData = test.docs.map(doc => ({
        id: doc.id, // 不需要ID可删除此行
        ...doc.data() // 展开文档实际数据字段
      }));
      setAnnotations(pureData);
    });
  }, []);

2. 适配PDF生成的遍历方式

现在Annotations是纯数据数组,可直接用map()或forEach()遍历,根据你使用的PDF生成库调整输出结构:

示例1:适配HTML转PDF库(如react-native-html-to-pdf)

const getPDFHtml = () => {
  if (!Annotations.length) return "";
  
  return Annotations.map(item => `
    <section style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #eee;">
      <h4>${item.title}</h4> <!-- 替换为你的实际字段名 -->
      <p>${item.content}</p>
      <p style="color: #666; font-size: 12px;">
        创建时间: ${new Date(item.createdAt.toDate()).toLocaleString()}
      </p>
    </section>
  `).join("");
};

示例2:适配原生PDF构建库(如react-native-pdf-lib)

import { PDFDocument, PDFPage } from 'react-native-pdf-lib';

const generatePDF = async () => {
  if (!Annotations.length) return;
  
  const pdfDoc = await PDFDocument.create();
  let currentY = 750; // 页面初始Y坐标
  const page = pdfDoc.addPage();

  Annotations.forEach(item => {
    // 添加标题
    page.drawText(item.title, {
      x: 40,
      y: currentY,
      fontSize: 16,
      color: '#222'
    });
    currentY -= 25;
    
    // 添加内容
    page.drawText(item.content, {
      x: 40,
      y: currentY,
      fontSize: 14,
      color: '#444'
    });
    currentY -= 40;
    
    // 添加时间
    page.drawText(new Date(item.createdAt.toDate()).toLocaleString(), {
      x: 40,
      y: currentY,
      fontSize: 12,
      color: '#666'
    });
    currentY -= 35;
  });

  const savedPath = await pdfDoc.save('notification_archive.pdf');
  // 后续处理:打开、分享PDF等
};

这样处理后,你就能得到无冗余的文档数据,且遍历逻辑完全适配PDF生成的需求。

内容的提问来源于stack exchange,提问作者aspidev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:35:35