试图递归地渲染评论ReactJs

问题描述

这是我的评论数据结构。我认为我的数据结构错误,无法递归呈现注释。请指教。我可以获得单条评论一个答复,但回信数量未知。

  "comments": [
    {
      "id": 1,"content": "This is so great!","recipe_id": 1,"commentable_id": 1,"commentable_type": "Recipe","user_id": 1,"created_at": "2020-09-08T00:16:55.296Z","updated_at": "2020-09-08T00:16:55.296Z"
    },{
      "id": 2,"content": "This is another one","commentable_type": "Comment","created_at": "2020-09-08T00:16:55.323Z","updated_at": "2020-09-08T00:16:55.323Z"
    },{
      "id": 3,"commentable_id": 2,"created_at": "2020-09-08T00:16:55.332Z","updated_at": "2020-09-08T00:16:55.332Z"
    },

解决方法

有两种方法可以实现此目的:

您可以将回复存储为评论的子代:

{
  id: 3,content: "this is a comment",replies: [
    {
      id: 1,content: "This is a reply"
    }
]

或者您可以将回复存储在与评论相同的级别。如果选择此方法,则将需要一个reply_to属性,如果该属性是答复,则应引用注释ID;如果是直接注释而不是答复,则应引用null(最好设置为未设置)。

您选择哪种方法取决于您的其余数据结构和应用行为。

,

假设您从API获得的数据结构是固定不变的,则可以从该平面数据中“添加”一棵注释树。我已省略了下面的用户ID和日期信息,以使内容更简短。

想法是<CommentBoxes>将注释列表呈现为<CommentBox>组件;注释的完整列表会传递出去,以确保<CommentBox>可以对其进行过滤,以找到要渲染的注释的子注释(如有)。

const commentData = [
  {
    id: 1,content: "This is so great!",recipe_id: 1,commentable_id: 1,commentable_type: "Recipe",},{
    id: 2,content: "This is another one",commentable_type: "Comment",{
    id: 3,commentable_id: 2,];

const CommentBox = ({ comment,allComments }) => {
  const children = allComments.filter(
    (c) => c.commentable_type === "Comment" && c.commentable_id === comment.id
  );
  return (
    <li>
      {comment.content}
      {children ? <CommentBoxes comments={children} allComments={allComments} /> : null}
    </li>
  );
};

const CommentBoxes = ({ comments,allComments }) => (
  <ul>
    {comments.map((c) => (
      <CommentBox comment={c} allComments={allComments} key={c.id} />
    ))}
  </ul>
);

const App = () => {
  const rootComments = commentData.filter((c) => c.commentable_type === "Recipe");
  return <CommentBoxes comments={rootComments} allComments={commentData} />;
};

ReactDOM.render(<App />,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...