即使数据存储在数据库中我也无法检索数据

问题描述 投票:0回答:1

我用mern stack创建了一个项目,当我尝试对客户端的帖子进行评论时,评论没有出现,即使它显示评论已成功完成,并且评论已保存在数据库中。

在我的一次尝试中,我能够在控制台上打印评论,但我无法让它们出现在页面上

评论应出现在帖子页面中

PostPage.jsx:

    const { pid } = useParams();

  const currentPost = posts[0];
  useEffect(() => {
    const getPost = async () => {
      setPosts([]);
      try {
        const res = await fetch(`/api/posts/${pid}`);
        const data = await res.json();
        if(data.error) {
          showToast("Error", data.error, "error");
          return;
        }
        setPosts([data]);
      } catch (error) {
        showToast("Error", error.message, "error");
      }
    }
    getPost();
  }, [pid, setPosts, showToast]);

  useEffect(() => {
    const getComment = async () => {
      setComments([]);
      try {
        const res = await fetch(`/api/comments/${pid}/comments`);
        const data = await res.json();
        if(data.error) {
          showToast("Error", data.error, "error");
          return;
        }
        console.log([data])
        setComments([data]);
      } catch (error) {
        showToast("Error", error.message, "error");
      }
    }
    getComment();
  }, [pid, setComments, showToast]);

return (
  ...page codes

  <Flex>
  
{comments?.length >= 0 && comments?.map((comment) => {
  return <Comment 
  key={comment?._id} 
  comment={comment} 
  lastComment={comment?._id === comments[comments?.length - 1]._id}
  />
})}
</Flex>

)

comment.jsx:

import { Avatar, Divider, Flex, Text } from "@chakra-ui/react";


const Comment = ({ comment, lastComment }) => {
  return (
    <>
    <Flex gap={4} py={2} my={2} w={"full"}>
        <Avatar src={comment.userProfilePic} size={"sm"}/>
        <Flex gap={1} w={"full"} flexDirection={"column"}>
            <Flex w={"full"} justifyContent={"space-between"} alignItems={"center"}>
                <Text fontSize={"sm"} fontWeight={"bold"}>
                    {comment.username}
                </Text>
                
            </Flex>
            <Text>{comment.comment}</Text>
        </Flex>
    </Flex>
    {!lastComment ? <Divider /> : null}
    </>
  )
}

export default Comment

commentController.js

const getComments = async (req, res) => {
        const id = req.params;
        try {
            if(id) {
            const comments = await Comment.find({ postId: id }).sort({ createdAt: -1 })
            res.json(comments);
            } else {
                res.status(404).json({ message: "Comments not found!" })
            }
        } catch (error) {
            
        }
    }

commentModel.js

import mongoose from "mongoose";
const ObjectId = mongoose.Types.ObjectId;

const commentSchema = mongoose.Schema({
    postId: {
    type: ObjectId,
    ref: "Post",
    required: true,
    },
    comment: {
        type: String,
        required: true,
    },
    replies: [{
        reply: {
            type: String,
            required: true,
        },
        username: {
            type: String,
            required: true,
        },
        commentId: {
            type: ObjectId,
            required: true,
        },
    }],
    username: {
        type: String,
        required: true,
    }
}, {
    timestamps: true
})

const Comment = mongoose.model('Comment', commentSchema);

export default Comment;
javascript reactjs node.js mern data-retrieval
1个回答
0
投票

根据提供的代码片段,问题似乎可能与您的

getPost
getComment
函数中的状态更新有关。从服务器获取数据时,您使用
setPosts([data])
setComments([data])
更新状态。这会将状态设置为直接包含所获取数据的数组,覆盖之前的状态。

如果您要获取帖子的评论,请务必考虑现有评论并相应更新状态,而不是完全替换它。

// PostPage.jsx

// ...

useEffect(() => {
  const getPost = async () => {
    try {
      const res = await fetch(`/api/posts/${pid}`);
      const data = await res.json();
      if (data.error) {
        showToast("Error", data.error, "error");
        return;
      }
      setPosts([data]);
    } catch (error) {
      showToast("Error", error.message, "error");
    }
  };
  getPost();
}, [pid, setPosts, showToast]);

useEffect(() => {
  const getComment = async () => {
    try {
      const res = await fetch(`/api/comments/${pid}/comments`);
      const data = await res.json();
      if (data.error) {
        showToast("Error", data.error, "error");
        return;
      }
      setComments(data); // Update state without overwriting existing comments
    } catch (error) {
      showToast("Error", error.message, "error");
    }
  };
  getComment();
}, [pid, setComments, showToast]);

// ...

// Comment.jsx

// ...

// Ensure comments is an array before mapping
{Array.isArray(comments) && comments.length > 0 && comments.map((comment) => {
  return <Comment 
    key={comment?._id} 
    comment={comment} 
    lastComment={comment?._id === comments[comments.length - 1]._id}
  />;
})}

// ...

此修改假设从服务器返回的注释是一个数组。确保服务器对评论的响应是一个数组,并且状态更新应该正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.