【问题标题】:React JS - Firestore: How to delete a document inside a collectionReact JS - Firestore:如何删除集合中的文档
【发布时间】:2021-09-21 05:18:08
【问题描述】:

您好,我试图从我的集合中删除一个特定文档,因为虽然我知道删除集合中具有特定 ID 的文档的代码(我正在阅读:Delete data from Cloud Firestore),显然我错了,很高兴它是一个测试集合。

所以我的问题是如何使用特定 ID 从集合中删除文档 首先这是我在我的集​​合中存储数据的方式:

const register = (e) => {
        e.preventDefault();

        const docId = `${descripcion}`;
        const docRef = db.collection('productosAIB').doc(docId);

        docRef.get().then((doc) => {

            if (doc.exists) 
            {
                window.alert("Ya existe ese producto")
            }
            else {
                docRef.set({
                    descripcion: descripcion,
                    grado: grado,
                    precio: precio,
                    cantidad: cantidad,
                    id: docRef.id
            }).then((r) => {
                window.alert("Producto agregado")
            })}
    })
}

所以我创建了一个名为 docID 的变量,它将获取用户可以通过输入发送的描述然后我确保创建的文档将是 doc.id 然后我将所有信息发送到数据库,这是最终结果:

  • 所有数据都是用户先插入的

  • 这就是它在 Firestore 中更新后的样子

  • 这是它在表格中的样子:

现在我创建了一个名为 deleteProduct 的函数,该函数旨在删除文档而不是整个集合:

const deleteProduct = (producto) => {
        db.collection("productosAIB").doc(producto).delete();
    }

这是渲染/打印表格和调用函数的地方 (注意:该函数在“”(引号)上,因为我不希望该函数运行,因为它会删除我刚刚创建的文档)

<tbody>
                {productos.map((productos, index) => (
                        <tr key={productos.id || index}>
                        <td>
                            <input className = "agregarAIB_cantidad"
                            onChange = {(e) => {changeCantidad(productos.descripcion, e.target.valueAsNumber)}}
                            type = 'number'
                            pattern = "[0-9]*"
                            required
                            value = {productos.cantidad}
                            />
                        </td>

                        <td>{productos.grado}</td>

                        <td >
                        {productos.descripcion}
                        </td>

                        <td >$
                        <input className = "agregarAIB_precio"
                            onChange = {(e) => {changePrecio(productos.descripcion, e.target.valueAsNumber)}}
                            type = 'number'
                            pattern = "[0-9]*"
                            required
                            value = {productos.precio}
                            />
                        </td>

                        <th>
                            <button onClick = "{deleteProduct(productos.descripcion)}"/> <-- This is the function
                        </th>
                        </tr>
                     ))
                     }
                </tbody>

现在奇怪的是(这就是我来这里询问的原因)是我什至没有单击按钮并运行了该功能(这就是为什么我现在将它放在引号中),这是因为在地图什么的?因为它对我来说没有任何意义,因为某种原因,它在不点击显示“OnClick”的按钮的情况下运行。

欢迎任何提示、文档和帮助,如果需要完整代码,请告诉我。

【问题讨论】:

    标签: javascript reactjs google-cloud-firestore


    【解决方案1】:

    把按钮元素改成这个

    &lt;button onClick = { ()=&gt;{deleteProduct(productos.descripcion)}}/&gt;

    您现在所做的会立即调用该函数。相反,您必须传递函数的一个实例。

    【讨论】:

    • 哦,我明白了,现在我傻了,但奇怪的是,实际上只是从其他地方复制并粘贴按钮,而在其他代码或 w/e 我没有这样做复制它。感谢您的帮助。
    • 如果您不必将任何参数传递给函数&lt;button onClick = {deleteProduct}/&gt;,则像这样直接传递函数将起作用。但是在函数立即调用它之后添加()。
    【解决方案2】:

    你可以这样做:

        your doc_id: docID = 123abc (anything);
        
        const handleDelete = async () => {
        try{
        await firebase.firestore().collection("collectionName").doc(docID).delete();
        console.log("record deleted");
        // update your state or anything you want to do after deletion
        }
        catch(error){
        console.log(error.message);
        }
    }
    
    //your Button:
    <Button onClick={()=>{deleteProduct(productos.descripcion)}}>Delete</Button>
    

    【讨论】:

      【解决方案3】:

      我建议在向 firebase 添加项目时使用 add() 函数,这样 firebase 会自动为您的文档生成一个唯一 ID。

      【讨论】:

      • 只要将数据推送到 Firestore,它就会生成一个随机 ID,对于这个项目,我手动为描述分配一个 ID =。感谢您的建议
      猜你喜欢
      • 2018-03-22
      • 2021-11-23
      • 2021-11-10
      • 2020-09-08
      • 2021-11-14
      • 2020-02-17
      • 2018-11-01
      相关资源
      最近更新 更多