所以我有一个社交媒体页面,其中有一系列存储在 sql 数据库中的帖子。每个帖子都有一个 ID、作者和正文。我有另一个数据库用于与某个帖子相关联的评论。我的问题是,将正在评论的帖子的 id 发送到评论数据库以便每个评论通过其 ID 链接到帖子的最佳方式是什么?当我稍后查询数据库时,我想显示每个帖子的评论,但不是数据库中的所有评论,只是与发布它的帖子相关联的评论。希望一切都说得通。这是我的一些代码,我愿意接受任何和所有建议。帖子组件:
import React, {useState, useContext} from 'react';
import {AuthContext} from '../AuthContext';
import './Post.css';
import axios from 'axios';
const Post = ({posts, getComment, comments, key}) => {
const {user} = useContext(AuthContext);
const {username} = user;
const [comment, setComment] = useState({
author: username,
comment: '',
id: need this to be the id from the posts that are being passed in as props,
});
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('/post/comment', comment);
getComment()
console.log(response);
} catch (error) {
console.error(error);
}
};
const onChange = (e) => {
setComment({...comment, [e.target.name]: e.target.value});
console.log(comment);
};
return (
<section>
<ul>
{posts.map((post) => (
<div className="postCard">
<p className="author">{post.author}</p>
<img src="" alt="" />
<div className="postBody">
<p>{post.body}</p>
</div>
<div className="comments">
<form action="submit" onSubmit={handleSubmit}>
<input
type="textarea"
name="comment"
onChange={onChange}
/>
<button>Comment</button>
</form>
<div>
{' '}
{comments.map((comment) => (
<div>
<p>{comment.author}</p>
</div>
))}
</div>
<p>
<i class="far fa-thumbs-up"></i>
</p>
</div>
</div>
))}
</ul>
</section>
);
};
export default Post;