首页 > 解决方案 > 无法迭代并将嵌套在“帖子”中的“评论”传递给组件

问题描述

我在来自 Rails 的名为“目击”的帖子中嵌套了“评论”。我将“目击”数组作为道具传递给SightingContainer,然后传递给SightingCard. 这一切都很好。然后我需要在同一张卡片中添加“评论”(评论是可评论的)。现在,我将其视为 App 的一个单独分支,并将一组“目击”(嵌套了评论)发送CommentsContainerCommentsCard. 在CommentContainer我进行 2 次迭代以深入到“评论”。

我是一个 React 新手,所以我可能没有正确实现这一点。

ComponentContainer接受数组props.sightings

import React from 'react';
import { Comment } from 'semantic-ui-react'
import CommentCard from '../components/CommentCard'


const CommentsContainer = props => {
  return (
    <div>
      {props.sightings && props.sightings.map(sighting => {
      return  sighting.comments.map((comment, idx) => {
        return <CommentCard key={idx} comment={comment} editComment={props.editComment}
          likeComment={props.likeComment} addComment={props.addComment}  currentUser={props.currentUser} deleteComment={props.deleteComment}/>
      })
    })
    }
    </div>
  )
};

export default CommentsContainer

我得到的错误是:


×
←→1 of 3 errors on the page
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

如果有人能告诉我一个更好的方法来实现这个,请指教!

标签: reactjscomponentsiterationpolymorphic-associations

解决方案


所以看起来整个 React 对嵌套数据的处理并不好。最好在后端处理它并将其作为非嵌套数据发送,即使它具有belongs_to或多态关系。


推荐阅读