You need to enable JavaScript to run this app. React搭配Firebase开发时无法从Firestore数据库删除数据问题求助
优惠活动
大模型
产品
解决方案
定价
更多

React搭配Firebase开发时无法从Firestore数据库删除数据问题求助

问题原因

你遇到的remove is not a function报错属于API调用混淆:

  • remove()是Firebase实时数据库(Realtime Database)的删除方法
  • Firestore中文档的删除方法为delete()
修正方案

直接替换handleDeleteQuantity中的删除逻辑即可,修正后的代码如下:

const handleDeleteQuantity = (product) => {
  firebase.firestore()
    .collection('products')
    .doc(product.id)
    .delete() // 把原来的remove()替换为delete()
    .then(() => {
      console.log(`商品id为${product.id}删除成功`)
    })
    .catch((error) => {
      console.error('删除失败:', error)
    })
}

注意:你已经通过onSnapshot监听了products集合的实时变化,数据库数据删除后,监听器会自动触发更新本地的products状态,不需要手动编写过滤逻辑更新本地状态,你注释掉的本地过滤代码可以直接移除。

额外优化提示

你当前useEffect里处理快照的逻辑存在小问题,先把数据push到数组再赋值id,极端场景下会出现id未正确挂载的情况,可以调整顺序:

useEffect(()=>{
  const ref = firebase.firestore().collection('products');
  ref.onSnapshot((snapshot) => {
    const items = [];
    snapshot.forEach((doc) =>{
      const data = doc.data();
      data['id'] = doc.id // 先赋值id
      items.push(data) // 再push到数组
    })
    setProducts(items);
  })
},[]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 21:27:00