提问人:Pepitos333 提问时间:11/6/2023 最后编辑:Pepitos333 更新时间:11/8/2023 访问量:30
在 nextjs 中发表评论部分时出现问题
Problems making comments section in nextjs
问:
在我使用 Nextjs 和 TypeScript 构建的 Web 应用程序中,我想包含一个评论部分,在我的路由中,我包含了 post 和 get 请求,完美运行,因为我使用 postman 测试了它们,在我的 page.tsx 组件中,控制台说 post 和 get 请求工作正常,就像服务器本身所说的那样,我得到了一个表格,我使用我的 post 请求并将评论保存在数据库中, 我现在的问题是获取评论并让它们进入屏幕。 在这里,我发布我的“api/comments/routes.ts”文件:
import Comment from "../../models/commentModel";
import { connectDB } from "@/app/config/dbConfig";
import { NextRequest, NextResponse } from "next/server";
connectDB();
export async function POST(request: NextRequest) {
try {
const reqBody = await request.json();
const { name, comment } = reqBody;
const newComment = new Comment({
name,
comment,
});
const data = await newComment.save();
return NextResponse.json({
message: "Comment created successfully",
sucess: true,
data: data,
});
} catch (err) {
console.log(err);
}
}
export async function GET(request: NextRequest) {
try {
const comments = await Comment.find();
return NextResponse.json(comments);
} catch (error: any) {
return NextResponse.json({ message: error.message }, { status: 500 });
}
}
这是我的前端组件,它给我带来了问题: “应用程序/评论部分/page.tsx”
"use client";
import React from "react";
import axios from "axios";
import { message } from "antd";
import { Button, Checkbox, Form, Input } from "antd";
import TuttiCommenti from "../components/TuttiCommenti";
export interface Valori {
_id: number;
name: string;
comment: string;
}
const Comments = () => {
const [loading, setLoading] = React.useState<boolean>(false);
const [comments, setComments] = React.useState([]);
const getComments = async () => {
try {
setLoading(true);
const response = await axios.get("/api/comments");
setComments(response.data);
console.log(comments)
console.log(response.data)
} catch (error: any) {
message.error(error.message);
} finally {
setLoading(false);
}
};
React.useEffect(() => {
getComments();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onSubmit = async (values: any[]) => {
await axios.post("/api/comments", values);
message.success("Comment added");
};
return (
<div className="maindiv h-[970px] bg-cover bg-[url('../../public/assets/sfondo.jpg')]">
<Form
name="basic"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
style={{ maxWidth: 600 }}
initialValues={{ remember: true }}
onFinish={onSubmit}
autoComplete="off"
>
<Form.Item<any>
label="name"
name="name"
rules={[{ required: true, message: "Please input your username!" }]}
>
<Input />
</Form.Item>
<Form.Item<any>
label="comment"
name="comment"
rules={[{ required: true, message: "Please input your comment!" }]}
>
<Input />
</Form.Item>
<Form.Item wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
{/* <div>
{comments.map((comment:any)=>(
<div key={comment._id}>
<TuttiCommenti comment={comment} />
</div>
))}
</div> */}
</div>
);
};
export default Comments;
我唯一的问题是填充组件顶部声明的注释数组,我还没有弄清楚。
甚至以这种方式发出 get 请求:
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
fetch('/api/comments')
.then((res) => res.json())
.then((data) => {
console.log(data);
setPosts(data);
console.log(posts)
})
.catch((err) => {
console.log(err.message);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
我在控制台中得到的是来自响应的数据,但它没有被拉入帖子变量中,真的不明白为什么
答: 暂无答案
评论