【发布时间】:2021-05-04 14:17:11
【问题描述】:
我正在尝试向帖子添加删除按钮,以便我可以从频道中删除单个帖子。我使用 Firebase 作为我的数据库,并且帖子集合嵌套在频道集合中。我为每个帖子添加了一个按钮,创建了一个名为 handleDel 的 onClick 事件,我尝试在频道集合中找到帖子并将其删除,但我无法删除我的帖子。
const db = firebaseApp.firestore()
Post.js
function Post({ user, post, timestamp }) {
const channelId = useSelector(selectChannelId)
const handleDel = () => {
db.collection('channels')
.doc(channelId)
.collection('posts')
.doc(post).delete().then(() => {
console.log("Document successfully deleted!");
}).catch((error) => {
console.error("Error removing document: ", error);
});
}
return (
<div className='post'>
<Avatar src={user.photo}
/>
<div className="post__content">
<h4>{user.displayName}
<span className='post__timestamp'>
<ClearIcon
className='clearIcon'
onClick={handleDel}
id={post.id}
/>
{new Date(timestamp?.toDate()).toUTCString()}
</span>
</h4>
<p className='post__text'>
{post}
</p>
</div>
</div>
)
}
Posts.js 了解更多上下文
function Posts() {
const user = useSelector(selectUser)
const channelId = useSelector(selectChannelId)
const channelName = useSelector(selectChannelName)
const [input, setInput] = useState('')
const [posts, setPosts] = useState([])
useEffect(() => {
if (channelId) {
db.collection('channels')
.doc(channelId)
.collection('posts')
.orderBy('timestamp', 'asc')
.onSnapshot((snapshot) =>
setPosts(snapshot.docs.map(doc => ({...doc.data(), id: doc.id})))
)
}
}, [channelId])
const sendPost = e => {
e.preventDefault()
db.collection('channels')
.doc(channelId)
.collection('posts')
.add({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
post: input,
user: user,
})
setInput('')
}
return (
<div className='posts__container'>
<ChannelTitle channelName={channelName} />
<div className="posts">
{posts.map((post) => (
<Post
timestamp={post.timestamp}
post={post.post}
user={post.user}
id={post.id}
key={post.id}
/>
))}
</div>
<div className="post__input">
<AddCircleIcon />
<form>
<input
type="text"
placeholder={`Post to #${channelName}`}
value={input}
disabled={!channelId}
onChange={e => setInput(e.target.value)}/>
<button
type='submit'
className='post__inputButton'
onClick={sendPost}>
Send</button>
</form>
<div className="post__inputIcons">
<GifIcon />
<EmojiEmotionsIcon />
</div>
</div>
</div>
)
}
我也试过
const handleDel = () => {
db.collection('posts')
.doc(post).delete().then(() => {
console.log("Document successfully deleted!");
}).catch((error) => {
console.error("Error removing document: ", error);
});
}
和
const handleDel = () => {
db.collection('channels')
.doc(channelId)
.collection('posts')
.doc(post.id).delete().then(() => {
console.log("Document successfully deleted!");
}).catch((error) => {
console.error("Error removing document: ", error);
});
}
我的控制台显示“文档已成功删除!”但该帖子仍在数据库中并且仍然显示。任何见解将不胜感激。
【问题讨论】:
标签: reactjs firebase redux react-redux