我一直在尝试使用Reactjs对firebase数据库进行删除操作。我有一个bug,我的函数从firebase抓取错误的id。
我有一个按钮,调用handleOpen函数打开一个模态。
模态操作:
// Grabs the right id
const [open, setOpen] = useState(false);
const handleOpen = (id) => {
console.log(id);
setOpen(true);
};
const handleClose = () => setOpen(false);
我有一个按钮,调用handleDelete函数,该函数获取文档id引用并删除文档引用。
handleDelete功能:
const handleDelete = (id) => {
const docRef = projectFirestore.collection("News").doc(id);
docRef.delete();
console.log("Deleted post data from id: " + id);
handleClose();
};
从我一直在观察handleDelete函数从映射的帖子数组中获取最后一个id,它不将当前文档的id传递给模态。
问题只发生在我在模态内部传递函数时。当我将函数传递到模态外部时,它工作得很好。
目标
获取文档id,将其传递给模态并删除相应的文档。
完整代码:
import React, { useState } from "react";
import { projectFirestore } from "../../../../firebase/config";
import { useCollectionData } from "react-firebase-hooks/firestore";
import Layout from "../../../../hoc/Layout/Layout";
import { Link } from "react-router-dom";
import { Button, Box, Modal } from "@mui/material";
const DeletePost = () => {
const docRef = projectFirestore.collection("News");
const query = docRef.orderBy("createdAt", "desc");
const [posts] = useCollectionData(query, { idField: "id" });
// Modal operations
const [open, setOpen] = useState(false);
const handleOpen = (id) => {
setOpen(true);
};
const handleClose = () => setOpen(false);
const handleDelete = (id) => {
const docRef = projectFirestore.collection("News").doc(id);
docRef.delete();
console.log("Deleted post data from id: " + id);
handleClose();
};
return (
<Layout>
<ul>
{posts &&
posts.map((post) => {
const data = post.createdAt.toDate();
const day = data.getUTCDate();
const month = data.getUTCMonth();
const year = data.getUTCFullYear();
return (
<li key={post.id}>
<div>
<h3>{post.id}</h3>
<img
src={post.url}
alt={post.title}
/>
<p>
<b>
{day}/{month}/{year}
</b>{" "}
{post.description}
</p>
</div>
<div>
<Link to="/edit-post">
<Button>
Edit Post
</Button>
</Link>
<Button onClick={() => handleOpen()}>
Delete Post
</Button>
<Modal
open={open}
onClose={handleClose}
aria-labelledby="Delete"
aria-describedby="Delete Post"
>
<Box>
<div>
<h4>
Are you sure you want to delete {post.title}?
</h4>
</div>
<div>
<Button
onClick={() => {
debugger;
handleDelete(post.id);
}}
>
Yes
</Button>
<Button onClick={handleClose}>
No
</Button>
</div>
</Box>
</Modal>
</div>
</li>
);
})}
</ul>
</Layout>
);
};
export default DeletePost;
您可以定义一个状态变量来跟踪当前正在编辑的ID:
const [selectedId, setSelectedId] = useState(-1);
然后编辑您的handleOpen
和handleClose
函数:
const handleOpen = (id) => {
setSelectedId(id);
setOpen(true);
};
const handleClose = () => {
setSelectedId(-1);
setOpen(false);
};
在handleDelete
功能中,如果选中了某个ID,则删除该ID:
const handleDelete = (id) => {
const docRef = projectFirestore.collection('News').doc(selectedId !== -1 ? selectedId : id);
docRef.delete();
console.log('Deleted post data from id: ' + id);
handleClose();
};
最后,需要通过添加id参数来更新JSX中的handleOpen
方法:
<Button onClick={() => handleOpen(post.id)}>
Delete Post
</Button>