现在我有一个应用程序,我想在其中检索帖子中的评论。我不知道什么是最好的方法。
我目前只显示带有评论的帖子,但不显示多个评论。
<Grid item xl={8}>
{this.props.posts.map((post, index) =>
<PostBodyTemplate key={index} postId={post.id} onSubmit={this.handleSubmit} onChange={e => this.handleInputChange(e,post.id,post.userId,post.userIdName)} title={post.title} postBody={post.postBody}
giphyUrl = {post.giphyUrl} userWhoPosted={post.userIdName} commentBody={post.commentBody} userIdName={post.userIdName} />
)}
{displayGifPicker ? (<AddGif selectedGif = {this.getGifState} />) : (<Button size="small" onClick={this.displayGifPicker} ><button>Add Gif</button></Button>)}
</Grid>
数据来自API,该API基本上将PostId和Comments表结合在一起,并通过PostId将它们连接起来,现在它仅显示一个注释,并且当前仅显示具有注释的Post。
router.get('/', (req, res) =>{
sequelize.query( "SELECT comments.id, comments.postId,
comments.commentBody, comments.giphyurl,
comments.postPicture,comments.userId, comments.userIdto,
comments.userIdName, comments.userIdtoName, posts.postBody, posts.title,
posts.giphyUrl, posts.postPicture, posts.userId, posts.userIdName,
posts.userIdto, posts.userIdtoName FROM comments INNER JOIN posts ON
comments.postId = posts.id;")
.then(([results, metadata]) => {
res.json(results)
})
})
我应该有更好的方法吗?解决我的问题的理想解决方案是抓取所有帖子,显示所有帖子,如果该帖子有评论,则还显示所有这些评论。我只有的查询返回带有评论的帖子,并且通过它们进行的映射仅显示一个评论,而不会显示所有评论。
要当前获取所有评论,我只是使用一个简单的findAll,但这并不会显示评论,因为这些评论位于评论表中。这就是为什么我在上一个查询中加入表的原因。
如果有帮助,这是道具被发送到的组件。
export default function PostBodyTemplate(props) {
const { onChange, onSubmit} = props
const classes = useStyles();
// render() {
return (
<Grid item xs={12} xl={8} lg={8} style={fr}>
<Card className={classes.card}>
<CardContent>
<Paper className={classes.root}>
<Typography variant="h5" component="h2" style={fr}>
{props.userWhoPosted} Gave A VH5 To Julio {props.postId}
</Typography>
<Typography variant="h5" component="h3">
{props.title}
</Typography>
<Typography component="p">
{props.postBody}
</Typography>
<img src={props.giphyUrl} style={giphyRes}/>
</Paper>
</CardContent>
<CardActions>
<IconButton aria-label="add to favorites">
<FavoriteIcon />
<div>Add Gif</div>
</IconButton>
<IconButton aria-label="share">
<EcoIcon />
<div>Add Photo</div>
</IconButton>
<form onSubmit={onSubmit}>
<div className={classes.container}>
<TextField
onChange = {onChange}
name='commentBody'
id="standard-full-width"
label="Reply To Post"
style={{ margin: 8 }}
placeholder="Reply to Post"
fullWidth
margin="normal"
InputLabelProps={{
shrink: true,
}}
/>
{/* <p><button>Send VH5</button></p> */}
{/* <Button onSubmit={onSubmit} size="small">Submit</Button> */}
<button onSubmit={onSubmit}>Submit VH5</button>
{/* <button onSubmit={onSubmit}>Submit Reply</button> */}
</div>
</form>
{/* <CommentInput onChange={onChange}/> */}
{/* <Button size="small">Submit</Button> */}
</CardActions>
<Paper className={classes.root} value={props.postId}>
<Typography variant="h5" component="h3">
{props.commentBody}
</Typography>
<Typography component="p">
{props.userIdName} replied to the post.
</Typography>
</Paper>
</Card>
</Grid>
)
// }
}