繁体   English   中英

FirebaseError:Function 使用无效数据调用 DocumentReference.update()。 不支持嵌套 arrays

[英]FirebaseError: Function DocumentReference.update() called with invalid data. Nested arrays are not supported

在此处输入图像描述 . 在此处输入图像描述 我正在尝试使用 firestore 通过我的 firebase 实现添加到购物车功能。

我有一个提取 function,它获取购物车中已经存在的任何现有项目。 但我只需要数组中的值,但是当我将它添加到我的 fectchedcartItems 列表时,它会创建一个嵌套数组,当我尝试更新购物车时它会给我带来问题,因为它不支持嵌套数组。 有没有办法只获取值而不创建嵌套数组? fetchItems = () => {

    Fire.shared.firestore.collection("cart").where("userId", "==", this.state.uid).get().then((qSnap) => {
        let itemList = []
        qSnap.docs.forEach(item => {
            itemList.push(item.data().items)
            this.setState({
                fetchedcartItems: itemList
            })

        })
       
        console.log("fectched product", this.state.fetchedcartItems);

    });

}


addItemToCart = () => {
    
        this.fetchItems()
        let items = this.state.fetchedcartItems

        items.push({ item: this.state.name, userId: this.state.uid })
        this.setState({
            items: items,
            fectchingitemsloading: true,
        },
            () => Fire.shared
                .firestore
                .collection('cart')
                .doc(this.state.cartId)
                .update({
                    items: items
                })
                .then(() => this.fetchItems())
        )

}
let itemList = []
qSnap.docs.forEach(item => {
  itemList.push(item.data().items)
  this.setState({
    fetchedcartItems: itemList
  })
})

item.date().items似乎是一个数组。 所以当你将一个数组推入另一个数组时,你会得到一个嵌套数组。 相反,您应该将单个项目推入数组,这样您最终只会得到一个顶层数组:

let itemList = [];
qSnap.docs.forEach(item => {
  itemList.push(...item.data().items) // <---- added spread syntax
})
// Moved the setState outside the loop; there's no need to set state multiple times
this.setState({
  fetchedcartItems: itemList
})

或者使用flatMap的替代方法:

let itemList = qSnap.docs.flatMap(item => item.data().items);
this.setState({
  fetchedcartItems: itemList
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM