我如何解决nextjs中的这个crud问题

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

我有一个使用 laravel sainttum api 运行的 nextjs app 目录应用程序,

我在我的 hooks/post.js 中做了这个

但问题是它不断向我的 api 发送请求。

非常感谢您的帮助

const getPost = async (postId) => {

        try {
            const response = await axios.get('api/posts/' + postId);
            return response.data.post;
        } catch (error) {
            if (error.response && error.response.status === 403) {
                throw new Error('Forbidden');
            } else {
                throw error;
            }
        }
    }

然后我在我的 EditForm 中做了这个

'use client'

import { usePosts } from "@/hooks/post"
import { useState } from "react"
import InputError from "@/components/InputError";
import styles from "../page.module.css";

const PostEditForm = ({params}) => {

    const { getPost } = usePosts();
    const { updatePost } = usePosts()

    const [post, setPost] = useState(null);
    const [title, setTitle] = useState('')
    const [body, setBody] = useState('')
    const [errors, setErrors] = useState([])

   const fetchPost = async () => {
        try{
            const postData = await getPost(params.id)

            setPost(postData)
            setTitle(postData.title)
            setBody(postData.body)
        }catch(error){

        }
   }


    fetchPost()

    const submitForm = async event => {
        event.preventDefault()

        await updatePost(params.id,{
            title,
            body,
            setErrors
        })
        
    }
next.js
1个回答
0
投票

检查该组件PostEditForm调用了多少次。

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