ShadCN 表单组件未在提交时发送请求

问题描述 投票:0回答:1

ShadCNui 表单组件在单击按钮(键入“提交”)时不会向数据库发送请求。 我使用 MongoDB 服务器来管理这一切。

但是我没有收到任何错误,我认为 onSubmit 根本没有被触发。当我单击提交按钮时,页面没有响应。我迷路了。 但是,用于不同功能的表单的相同(几乎)副本在向数据库发送请求时工作得非常好。只有当表单与页面的其他组件内联时,我才会发现问题。

正如我所说,我在终端或控制台中没有收到任何错误,因此我认为这一定是逻辑错误。我哪里出错了??

进口没有任何问题。

这是代码:

Page.tsx:

async function page({ params }: { params: { id: string } }) {
if (!params.id) return null;

    const user = await currentUser();
    if (!user) return null;
    
    const userInfo = await fetchUser(user.id);
    if (!userInfo?.onboarded) redirect("/onboarding");
    
    const thread = await fetchThreadById(params.id);
    
    return (
        <section className="relative">
            <div>
                <ThreadCard
                    id={thread._id}
                    currentUserId={user.id}
                    parentId={thread.parentId}
                    content={thread.text}
                    author={thread.author}
                    community={thread.community}
                    createdAt={thread.createdAt}
                    comments={thread.children}
                />
            </div>
    
            <div className="mt-7">
                <Comment
                    threadId={thread.id}
                    currentUserImg={user.imageUrl}
                    currentUserId={JSON.stringify(userInfo._id)}
                />
            </div>
        </section>
    );

}

export default page;

interface Props {
    threadId: string;
    currentUserImg: string;
    currentUserId: string;
}

function Comment({ threadId, currentUserImg, currentUserId }: Props) {
    const pathname = usePathname();

    const form = useForm<z.infer<typeof CommentValidation>>({
        resolver: zodResolver(CommentValidation),
        defaultValues: {
            thread: "",
        },
    });

    const onSubmit = async (values: z.infer<typeof CommentValidation>) => {
        await addCommentToThread(
            threadId,
            values.thread,
            JSON.parse(currentUserId),
            pathname
        );

        form.reset();
    };

    return (
        <Form {...form}>
            <form
                className="comment-form"
                onSubmit={form.handleSubmit(onSubmit)}
            >
                <FormField
                    control={form.control}
                    name="thread"
                    render={({ field }) => (
                        <FormItem className="flex w-full items-center gap-3">
                            <FormLabel>
                                <Image
                                    src={currentUserImg}
                                    alt="current_user"
                                    width={48}
                                    height={48}
                                    className="rounded-full object-cover"
                                />
                            </FormLabel>
                            <FormControl className="border-none bg-transparent">
                                <Input
                                    type="text"
                                    placeholder="Comment..."
                                    className="no-focus text-light-1 outline-none"
                                    {...field}
                                />
                            </FormControl>
                        </FormItem>
                    )}
                />

                <Button type="submit" className="active:bg-slate-600">
                    Reply
                </Button>
            </form>
        </Form>
    );
}

export default Comment;`

这是 ZResolver:


export const CommentValidation = z.object({
    thread: z.string().nonempty().min(3, { message: "Minimum 3 characters." }),
});

这是 onSubmit 内部的函数:


 export async function fetchThreadById(id: string) {
    connectToDB();

    try {
        //TODO: Populate Community
        const thread = await Thread.findById(id)
            .populate({
                path: "author",
                model: User,
                select: "_id id name image",
            })
            .populate({
                path: "children",
                populate: [
                    {
                        path: "author",
                        model: User,
                        select: "_id id name parentId image",
                    },
                    {
                        path: "children",
                        model: Thread,
                        populate: {
                            path: "author",
                            model: User,
                            select: "_id id name parentId image",
                        },
                    },
                ],
            })
            .exec();

        return thread;
    } catch (error: any) {
        throw new Error(`Error fetching thread: ${error.mesage}`);
    }
}

export async function addCommentToThread(
    threadId: string,
    commentText: string,
    userId: string,
    path: string
) {
    connectToDB();

    try {
        // Find the original thread by its ID
        const originalThread = await Thread.findById(threadId);

        if (!originalThread) {
            throw new Error("Thread not found");
        }

        // Create the new comment thread
        const commentThread = new Thread({
            text: commentText,
            author: userId,
            parentId: threadId, // Set the parentId to the original thread's ID
        });

        // Save the comment thread to the database
        const savedCommentThread = await commentThread.save();

        // Add the comment thread's ID to the original thread's children array
        originalThread.children.push(savedCommentThread._id);

        // Save the updated original thread to the database
        await originalThread.save();

        revalidatePath(path);
    } catch (err) {
        console.error("Error while adding comment:", err);
        throw new Error("Unable to add comment");
    }
} 
reactjs mongodb next.js react-hooks shadcnui
1个回答
0
投票

很抱歉在这里发布此内容,因为我没有足够的声誉来发表评论,但是您找到解决方案了吗?

© www.soinside.com 2019 - 2024. All rights reserved.