对每篇新闻帖子做出无限/最高级别的评论



>我有一个新闻功能,用户可以在其中发布他们的状态。但是,到目前为止,我无法使其显示新闻的所有评论,因为我当前的解决方案仅允许两级。这是我的代码:

新闻.js(全民)

function News() {
const {userId, setUserId} = useContext(UserContext);
const {type, isUserType} = useContext(UserTypeContext);
const [newsList, setNewsList] = useState([]);
const rootNews = newsList.filter(
(newList) => newList.reply_of === null
);
const getReplies = commentId => {
return newsList.filter(newList => newList.reply_of === commentId);
}

useEffect(()=>{

Axios.get('http://localhost:3001/news',{  
})
.then((response) => {
if(response.data.length > 0){
setNewsList(response.data);

}
})
},[]);
return (
<div className = "news p-5">
<h3 className="news-title">News</h3>
<div className = "comments-container">
{rootNews.map((rootNew) => (
<div>
<Comment key={rootNew.news_id} 
comment={rootNew}
replies={getReplies(rootNew.news_id)}/>
</div>
))}
</div>
</div>
)
}

评论.js(用于呈现评论和回复)

function Comment({comment, replies}) {
return (
<div className="comment">
<div className="comment-image-container">
<img src = "/user-icon.png" />
</div>
<div className="comment-right-part">
<div className="comment-content">
<div className="comment-author">
{comment.user_name}
</div>
<div>{comment.day}, {moment(comment.date).format('DD-MM-YYYY')} at {comment.time}</div>
</div>
<div className="comment-text">{comment.news_title}</div>
{replies.length > 0 && (
<div className="replies">
{replies.map(reply => (
<Comment comment={reply} key={reply.news_id} replies={[]}/>
))}
</div>
)}
</div>
</div>
)
}

下面是注释结构的示例:

Comment 1
Reply 1.1
Reply 1.1.1
Reply 1.1.1.1
Reply 1.2
Comment 2

关于如何呈现无限回复或可能设置允许的最大回复级别的想法?谢谢

你只需要对Comment组件进行一些更改,就可以递归地呈现已经嵌套的数据结构:

function Comment({ comment, newsList }) {

const replies = newsList.filter((newList) => newList.reply_of === comment.news_id);
return (
<div className="comment">
<div className="comment-image-container">
<img src="/user-icon.png" />
</div>
<div className="comment-right-part">
<div className="comment-content">
<div className="comment-author">{comment.user_name}</div>
<div>
{comment.day}, {moment(comment.date).format("DD-MM-YYYY")} at{" "}
{comment.time}
</div>
</div>
<div className="comment-text">{comment.news_title}</div>
{replies.length > 0 && (
<div className="replies">
{replies.map((reply) => (
<Comment key={reply.news_id} comment={reply} newsList={newsList} />
))}
</div>
)}
</div>
</div>
);
}

基本上,您只需将获取对注释的直接回复的代码移动到Comment组件中。

呈现根Comment组件时,将标识对根注释的所有直接回复,并将导致呈现嵌套Comment组件,而嵌套组件又将标识对回复的回复,呈现嵌套Comment组件等。

最新更新