嘿,我对编程很陌生,我正试图解决这个问题,但我陷入困境。
问题在于,当我从Feed中点击一个帖子时,点击功能会同时获取并显示相应帖子下方的所有其他评论...我想要完成的是onClick显示对相关帖子的评论,并在点击其他帖子时将其隐藏。
此外,我需要显示一个按钮"加载更多"每次出现一组注释并在点击时获取最新的10条注释。
任何帮助,关于如何保持清洁和可读性的建议将不胜感激!
提前谢谢你;
:)
以下代码:
import React from "react";
import axios from "axios";
const postsID = "/posts";
const commentsID = "/comments";
var postsURL = `https://jsonplaceholder.typicode.com${postsID}`;
var commentsURL = `https://jsonplaceholder.typicode.com${commentsID}`;
class Posts extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
comments: [],
expanded: false,
commentsToShow: 3
};
this.clicked = this.clicked.bind(this);
}
/*
showMoreComments() {
}
*/
clicked() {
axios.get(commentsURL).then(res => {
console.log("comments:", res);
this.setState({ comments: res.data });
});
}
componentDidMount() {
axios.get(postsURL).then(res => {
console.log("posts:", res);
this.setState({ posts: res.data });
});
}
render() {
//console.log('VARIABLE WORKING!', postsURL);
return (
<div className="container">
<div className="jumbotron-div col s12">
<ul className="collection">
{this.state.posts.slice(0, 10).map(post => (
<div>
<div key={post.id} onClick={this.clicked}>
<h5>User ID: {post.id}</h5>
<p>Post: {post.body}</p>
</div>
<div>
<ul className="collection">
{this.state.comments
.filter(comment => comment.postId === post.id)
.slice(0, 3)
.map(comment => (
<li key={comment.id}>
<p>Comment ID: {comment.postId}</p>
<p>Comment: {comment.body}</p>
</li>
))}
</ul>
</div>
</div>
))}
</ul>
</div>
</div>
);
}
}
export default Posts;
答案 0 :(得分:0)
如果帖子可以显示其评论或隐藏它,那么它肯定需要自己的状态。因此,它需要是一个自己的组件,例如:
class Post extends React.Component {
constructor(props) {
super(props);
this.state = { showComents: false };
}
render() {
const { id, body, comments } = this.props;
return (
<div key={id} onClick={() => this.setState({showComments: true })}>
<h5>User ID: {id}</h5>
<p>Post: {body}</p>
</div>
<div>
<ul className="collection">
{this.state.showComments ? comments.slice(0, 3)
.map(comment => (
<li key={comment.id}>
<p>Comment ID: {comment.postId}</p>
<p>Comment: {comment.body}</p>
</li>
)) : ""}
</ul>
</div>
</div>
))}
);
}
}
然后在帖子中使用<Post />
并传递帖子所需的所有数据。