javascript - 刷新页面后内容消失
问题描述
我有一个分为两部分的博客应用程序。第一部分是人们可以写实际博客的地方(标题、简短描述、正文、单击提交按钮),然后该博客与所有其他博客一起显示在屏幕上。这些博客是可点击的,可以查看。这部分工作得很好。如果人们点击博客,他们可以对其发表评论。它的工作方式类似于您可以编写博客的部分(人们写评论,单击提交按钮,它会显示在博客文章下方)。一切都存储在firebase中。问题是当我在评论部分刷新页面时,一切都消失了,我没有收到错误消息。如果我不刷新评论部分一切正常,但刷新后一切都消失了,但没有显示错误消息。
以下是评论部分的组件: CommentHolder 负责显示与实际博客文章相关的评论
import React from 'react';
import { projectFirestore } from '../../firebase/config';
import DeleteComment from './DeleteComment'
class CommentHolder extends React.Component {
state = { docs: [] }
_isMounted = false;
componentDidMount = () => {
const fetchDataFromFireBase = async () => {
const getData = await projectFirestore.collection("Comments")
getData.onSnapshot((querySnapshot) => {
var documents = [];
querySnapshot.forEach((doc) => {
documents.push({ ...doc.data(), id: doc.id });
});
if (this._isMounted) {
this.setState({ docs: documents })
}
});
}
fetchDataFromFireBase()
this._isMounted = true;
}
componentWillUnmount = () => {
this._isMounted = false;
}
renderContent() {
// Delete comments
const deleteComment = async (id) => {
projectFirestore.collection('Comments').doc(id).delete().then(() => {
console.log(`Blog with id: ${id} has been successfully deleted!`)
})
}
// Build comments
let user;
if (localStorage.getItem('user') === null) {
user = [];
} else {
user = JSON.parse(localStorage.getItem('user'));
const commentArray = this.state.docs?.filter(value => value.blogID === this.props.param);
const orderedComments = commentArray.sort((a, b) => (a.time > b.time) ? -1 : (b.time > a.time) ? 1 : 0);
const renderComments = orderedComments.map(comment => {
return (
<div key={comment.id} className="card mb-3" >
<div className="card-body">
<div className="row">
<div className="col-sm">
<h6>{`${comment.name} - ${comment.time}`}</h6>
<p>{comment.comment}</p>
</div>
<div className="col-sm text-right">
{user[0].id === comment.userID ? <DeleteComment commentid={comment.id} onDeleteComment={deleteComment} /> : ''}
</div>
</div>
</div>
</div>
)
})
const updateComments = () => {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString)
const id = urlParams.get('id')
const updateComment = projectFirestore.collection('Blogs').doc(id);
return updateComment.update({
'post.comments': commentArray.length
})
}
updateComments()
return renderComments;
}
}
render() {
return (
<div>
{this.renderContent()}
</div>
)
}
}
export default CommentHolder
AddComment 包含整个部分、文本区域、提交按钮和评论容器
import React, { useState } from 'react'
import SubmitComment from './SubmitComment'
import CommentHolder from './CommentHolder';
import { useSelector, useDispatch } from 'react-redux';
const AddComment = ({ param }) => {
const [comment, setComment] = useState('');
const dispatch = useDispatch();
const state = useSelector((state) => state.state);
if(state) {
setTimeout(() => {
setComment('')
dispatch({ type: "SET_FALSE" })
}, 50)
}
return (
<div>
<div>
<div className="row">
<div className="col-sm">
<div className="form-group">
<textarea rows="4" cols="50" placeholder="Comment" className="form-control mb-3" value={comment} onChange={(e) => setComment(e.target.value)} />
</div>
</div>
</div>
</div>
<div className="mb-3">
<SubmitComment comment={comment} param={param} />
</div>
<CommentHolder param={param} />
</div>
)
}
export default AddComment
SubmitComment 负责将评论提交到firebase
import React from 'react'
import { projectFirestore } from '../../firebase/config';
import { v4 as uuidv4 } from 'uuid';
import { useDispatch } from 'react-redux';
const SubmitComment = ({ comment, param }) => {
const dispatch = useDispatch();
const onCommentSubmit = () => {
let user;
if (localStorage.getItem('user') === null) {
user = [];
} else {
user = JSON.parse(localStorage.getItem('user'));
projectFirestore.collection('Comments').doc().set({
id: uuidv4(),
comment,
name: `${user[0].firstName} ${user[0].lastName}`,
userID: user[0].id,
blogID: param,
time: new Date().toLocaleString()
})
dispatch({ type: "SET_TRUE" });
}
}
return (
<div>
<button onClick={() => onCommentSubmit()} className='btn btn-primary'>Add comment</button>
</div>
)
}
export default SubmitComment
DeleteComment 只是删除评论
import React from 'react'
const DeleteComment = ({ commentid, onDeleteComment }) => {
return (
<div>
<button onClick={() => onDeleteComment(commentid)} className='btn btn-outline-danger'>X</button>
</div>
)
}
export default DeleteComment
你们对如何解决这个问题有什么建议吗?谢谢你。
解决方案
推荐阅读
- c++ - QT5 Signals 不会激活 SLOT 内的功能
- sql - 获取特定时间和日期的 systime - Oracle SQL
- node.js - 如何在父进程中捕获子进程 stderr 数据?
- vue.js - 如何使用 vuejs 执行服务器命令?
- javascript - 更改下载文件 javascript 所需的点击量
- sql - 有没有一种简单的方法可以将 name:value 子级转换为 postgresql 中的列?
- ios - 快速降低视频比特率
- r - 无法进行转换以应用我的 PCA 模型
- c - 在主 .c 文件中调用 Packet_Get() 函数时出错
- postgresql - Postgres 会话数据异常