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

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

. 我正在尝试使用 firestore 通过我的 firebase 实现添加到购物车功能。

我有一个获取功能,可以获取购物车中已有的任何现有商品。但我只需要数组 items 中的值,但是当我将它添加到我的 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
})