我有一个社交媒体应用程序,我希望它的功能类似于 Facebook,您可以在其中发表评论,并且评论会实时加载,而无需刷新浏览器即可显示评论。我能够将数据从 React 发送到后端服务器,并且能够通过 axios http 请求获取该数据,但我必须刷新浏览器才能看到显示的评论。我也多次看到评论显示。我没有收到任何错误,但评论并不是帖子所独有的,因为它是加载帖子的数组。我的代码有错误吗?
这是前端代码。
import React, { useState, useEffect } from "react";
import Container from "react-bootstrap/Container";
import Card from "react-bootstrap/Card";
import Button from "react-bootstrap/Button";
import axios from "axios";
import "./css/sharewall.css";
const ComponentName = () => {
const [posts, setPosts] = useState([]);
const [comment, setComment] = useState("");
const [id, setId] = useState("");
const loadData = async () => {
try {
let res = await axios.get(`http://localhost:5000/getall`);
setPosts(res.data);
} catch (error) {
console.log(error);
}
};
function makeRequest(e) {
e.preventDefault();
axios({
method: "POST",
url: "http://localhost:5000/postinput",
data: {
comment: comment,
},
}).then((res) => {
setComment(res.data.comment);
console.log(res.data);
});
}
const loadComment = async () => {
try {
let res = await axios.post("http://localhost:5000/postinput");
setComment(res.data.comment._id);
console.log(res.data.comment._id)
} catch (error) {
console.log(error);
}
};
useEffect(() => {
loadData();
}, []);
return (
<div className="compoentclass">
<Container className="mt-5 ml-auto mr-auto">
<div className="text-center">
{posts.map((post, index) => (
<div>
<Card className="">
<Card.Img alt="" src={post.url} />
<Card.ImgOverlay className="overlay">
<Card.Title className="text-center mt-5">
<Card.Text className="cardStyle text-light">
{post.body}
</Card.Text>
</Card.Title>
</Card.ImgOverlay>
</Card>
{posts.map((post, index) => (
<div><Card.Text>{post.comment}</Card.Text></div>
))}
<textarea
className="comment text-center mt-3 mb-3"
onChange={e => setComment(e.target.value)}
value={comment}
name={"comment"}
type={"text"}
/>
<div className="d-flex justify-content-start mt-n3 mb-4">
<Button
className="shareButton"
variant="secondary"
onClick={makeRequest}
onChange={loadComment}
>
Comment
</Button>
</div>
</div>
))}
</div>
</Container>
</div>
);
};
export default ComponentName;
最佳答案
为了让其他用户(发表评论的用户应该能够立即看到评论)实时看到评论,您必须在服务器/数据库中实现某种“监听器”来监听新评论。否则,我的浏览器怎么知道你刚才发表了评论?查看socket.io ,它很容易实现。
关于reactjs - 实时加载评论时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66578314/