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

React Native中Firebase子集合仅添加单个商品问题求助

React Native中Firebase批量添加子集合文档仅成功一个的问题排查与修复

问题描述

需要在Firebase的Orders集合下的Products子集合中添加购物车内的两个商品,但React Native环境下仅成功添加一个,相同逻辑在Expo应用中可正常运行。

React Native问题代码

const user = useSelector(state => state.userLogged.data);
const loggedUser = useSelector(state => state.authUser.authenticated);
const cartProducts = useSelector(state => state.cart);
console.log(typeof cartProducts);
const placeOrder = async () => {
    let orderId;
    let doc = await firestore()
        .collection('Orders')
        .add({
            totalPrice: route?.params?.orderPrice,
            userId: loggedUser,
            createdAt: firestore.FieldValue.serverTimestamp(),
        })
     const orderId = doc.id;
    for (const key in cartProducts) {
        doc = await firestore()
            .collection('Orders')
            .doc(orderId)
            .collection('Products')
            .add({
                productTitle: cartProducts[key].title,
                productImage: cartProducts[key].image[0],
                productQuantity: cartProducts[key].quantity,
                productPrice: cartProducts[key].price,
                productOfferPrice: cartProducts[key].offerPrice,
            });
    }
};

Expo正常工作代码

const createOrder = async () => {
    try {
        let orderID;
        const ordrRef = collection(db, "Order")
        await addDoc(ordrRef, {
            total: cartItemTotalAmount,
            userId: userID,
            timestamp: serverTimestamp()
        }).then((doc) => {
            orderID = doc.id
        })

        for (const key in cartItems) {
            await addDoc(collection(ordrRef, orderID, "products"), {
                productTitle: cartItems[key].productTitle,
                productPrice: cartItems[key].productPrice,
                quantity: cartItems[key].quantity
            })
            dispatch(cartActions.clearCart());

        }
    } catch (error) {
        console.log("Error", error)
    }
}

问题排查与修复方案

1. 修复变量重复声明问题

React Native代码中先声明了let orderId;,后续又用const orderId = doc.id;重复声明同名变量,这会导致作用域异常,甚至在严格模式下直接报错。应改为直接赋值:

const placeOrder = async () => {
    let orderId;
    // 重命名变量避免复用混淆
    const orderDoc = await firestore()
        .collection('Orders')
        .add({
            totalPrice: route?.params?.orderPrice,
            userId: loggedUser,
            createdAt: firestore.FieldValue.serverTimestamp(),
        })
    orderId = orderDoc.id; // 去掉const,直接赋值给已声明的变量
    for (const key in cartProducts) {
        await firestore()
            .collection('Orders')
            .doc(orderId)
            .collection('Products')
            .add({
                productTitle: cartProducts[key].title,
                productImage: cartProducts[key].image[0],
                productQuantity: cartProducts[key].quantity,
                productPrice: cartProducts[key].price,
                productOfferPrice: cartProducts[key].offerPrice,
            });
    }
};

2. 添加错误捕获逻辑

Expo代码有try/catch处理异常,而React Native代码缺少错误捕获,若某个商品添加失败会直接中断循环。添加错误捕获可定位问题:

const placeOrder = async () => {
    try {
        let orderId;
        const orderDoc = await firestore()
            .collection('Orders')
            .add({
                totalPrice: route?.params?.orderPrice,
                userId: loggedUser,
                createdAt: firestore.FieldValue.serverTimestamp(),
            })
        orderId = orderDoc.id;
        for (const key in cartProducts) {
            console.log(`正在添加商品:${cartProducts[key].title}`); // 日志辅助排查
            await firestore()
                .collection('Orders')
                .doc(orderId)
                .collection('Products')
                .add({
                    productTitle: cartProducts[key].title,
                    productImage: cartProducts[key].image[0],
                    productQuantity: cartProducts[key].quantity,
                    productPrice: cartProducts[key].price,
                    productOfferPrice: cartProducts[key].offerPrice,
                });
        }
        // 可选:添加成功后清空购物车
        // dispatch(cartActions.clearCart());
    } catch (error) {
        console.error("下单失败:", error);
    }
};

3. 确认购物车数据结构适配循环

检查cartProducts的数据类型:

  • 如果是对象,保留for...in循环;
  • 如果是数组,改用for...of循环:
// 若cartProducts是数组
for (const product of cartProducts) {
    await firestore()
        .collection('Orders')
        .doc(orderId)
        .collection('Products')
        .add({
            productTitle: product.title,
            productImage: product.image[0],
            productQuantity: product.quantity,
            productPrice: product.price,
            productOfferPrice: product.offerPrice,
        });
}

总结

核心问题是变量重复声明导致orderId作用域异常,加上缺少错误处理无法定位中断原因。修改变量声明方式、添加错误捕获后,即可解决仅添加一个商品的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:16:34