next.js TypeError:Cannot destruct property 'blog' of 'param',因为它是未定义的

j7dteeu8  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(137)

我正在用NextJS和Strapi做博客。我正在为我的博客文章做评论功能。但是,我犯了两个奇怪的错误:TypeError: Cannot destructure property 'blog' of 'param' as it is undefined.AxiosError: Request failed with status code 404。下面是BlogPost的代码:

import Image from "next/image";
import { api } from "../../../../http";
import ReactMarkdown from "react-markdown";
import SubmitComment from "@/components/SubmitComment";

const BlogPost = async ({ params: { slug } }: any) => {
  const { data } = await api.get(`/api/blogs?filters[slug]=${slug}&populate=*`);
  const blog = data.data[0]
  return (
    <div className="lg:max-w-screen-xl container mx-auto px-2">
      <div className="w-full py-10 bg-white min-h-screen">
        <div>
          <Image
            width={1000}
            height={800}
            alt="Image"
            className="mx-auto py-2 px-2"
            src={blog.attributes.main_image.data.attributes.url}
          />
          <div className="mx-10">
            <h1 className="text-5xl my-2 font-lato font-semibold">
              {blog.attributes.title}
            </h1>
            <ReactMarkdown
              className="my-2 markdown"
              children={blog.attributes.body}
            />
          </div>
        </div>
      </div>
      <div className="w-full my-2 py-10 bg-white">
        <SubmitComment blog={blog} />
      </div>
    </div>
  );
};

export default BlogPost;

在nextjs 13中,useState用于客户端组件,我单独制作了注解组件。这就是代码:

"use client"

import { useState } from "react";
import { api } from "../../http";

const SubmitComment = async ({blog}:any) => {
  const [name, setName] = useState<string>('')
  const [email, setEmail] = useState<string>('')
  const [comment, setComment] = useState<string>('')
  const res = await api.post('/api/comments', {
    name,
    email_id: email,
    comment,
    blog: blog.id
  })
  console.log(res)
  return (
    <div>
      <div className="grid lg:grid-cols-2 grid-cols-1 gap-2">
        <input
          type="name"
          name="name"
          className="ml-2 bg-gray-100 h-8 rounded-full px-2 text-lg"
          placeholder="Your name"
          onChange={(e)=>{setName(e.target.name)}}
        />
        <input
          type="email"
          name="email"
          className="mr-2 bg-gray-100 h-8 rounded-full px-2 text-lg"
          placeholder="Your Email ID"
          onChange={(e)=>{setEmail(e.target.name)}}
        />
        <textarea
          className="mx-2 lg:col-span-2 bg-gray-100 rounded-lg px-2 text-lg"
          placeholder="Comment"
          rows={5}
          onChange={(e)=>{setComment(e.target.name)}}
        ></textarea>
      </div>
      <div className="flex justify-center my-2">
        <button type="submit" className="button">
          Submit
        </button>
      </div>
    </div>
  );
};

export default SubmitComment;

下面是实际的json blogpost响应:

{
  "data": [
    {
      "id": 2,
      "attributes": {
        "title": "Why do Red Giants expand ?",
        "body": "Red giants expand because of a change in the balance of forces within the star. When a star is on the main sequence, it is fusing hydrogen in its core. This fusion reaction produces a lot of energy, which keeps the star's core hot and prevents it from collapsing.\n\nHowever, once the star's core runs out of hydrogen, the fusion reaction stops. This causes the core to cool and contract. As the core contracts, it becomes denser and hotter. This heat causes the outer layers of the star to expand.\n\nThe expansion of the outer layers is caused by a combination of factors. First, the heat from the contracting core causes the gas in the outer layers to expand. Second, the gravity of the star is not strong enough to hold the outer layers in place, so they expand.\n\nThe expansion of the outer layers causes the star to become much larger and brighter. This is why red giants are so much larger and brighter than main sequence stars.\n\nThe expansion of red giants is a temporary phase in the life of a star. Eventually, the outer layers of the star will be ejected into space, leaving behind a white dwarf or a neutron star.\n\n**Here is a summary of the reasons why red giants expand:**\n\n- The core of the star contracts and becomes denser, which releases heat.\n- The heat from the contracting core causes the outer layers of the star to expand.\n- The gravity of the star is not strong enough to hold the outer layers in place, so they expand.\n- The expansion of red giants is a fascinating phenomenon that helps us to understand the life cycle of stars. It is also a reminder that even the most stable stars are constantly changing and evolving.\n\n",
        "slug": "why-does-red-giants-expand",
        "createdAt": "2023-06-16T12:11:54.069Z",
        "updatedAt": "2023-06-17T11:13:30.105Z",
        "publishedAt": "2023-06-16T14:21:48.839Z",
        "main_image": {
          "data": {
            "id": 3,
            "attributes": {
              "name": "scientists-witness-red-giant-star-explode-real-time-first-time-ever.jpg",
              "alternativeText": null,
              "caption": null,
              "width": 784,
              "height": 441,
              "formats": {
                "small": {
                  "ext": ".jpg",
                  "url": "https://res.cloudinary.com/djpxkfscg/image/upload/v1686925296/small_scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035.jpg",
                  "hash": "small_scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035",
                  "mime": "image/jpeg",
                  "name": "small_scientists-witness-red-giant-star-explode-real-time-first-time-ever.jpg",
                  "path": null,
                  "size": 31.72,
                  "width": 500,
                  "height": 281,
                  "provider_metadata": {
                    "public_id": "small_scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035",
                    "resource_type": "image"
                  }
                },
                "medium": {
                  "ext": ".jpg",
                  "url": "https://res.cloudinary.com/djpxkfscg/image/upload/v1686925296/medium_scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035.jpg",
                  "hash": "medium_scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035",
                  "mime": "image/jpeg",
                  "name": "medium_scientists-witness-red-giant-star-explode-real-time-first-time-ever.jpg",
                  "path": null,
                  "size": 62.85,
                  "width": 750,
                  "height": 422,
                  "provider_metadata": {
                    "public_id": "medium_scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035",
                    "resource_type": "image"
                  }
                },
                "thumbnail": {
                  "ext": ".jpg",
                  "url": "https://res.cloudinary.com/djpxkfscg/image/upload/v1686925296/thumbnail_scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035.jpg",
                  "hash": "thumbnail_scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035",
                  "mime": "image/jpeg",
                  "name": "thumbnail_scientists-witness-red-giant-star-explode-real-time-first-time-ever.jpg",
                  "path": null,
                  "size": 8.04,
                  "width": 245,
                  "height": 138,
                  "provider_metadata": {
                    "public_id": "thumbnail_scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035",
                    "resource_type": "image"
                  }
                }
              },
              "hash": "scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035",
              "ext": ".jpg",
              "mime": "image/jpeg",
              "size": 70.11,
              "url": "https://res.cloudinary.com/djpxkfscg/image/upload/v1686925296/scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035.jpg",
              "previewUrl": null,
              "provider": "cloudinary",
              "provider_metadata": {
                "public_id": "scientists_witness_red_giant_star_explode_real_time_first_time_ever_ef95780035",
                "resource_type": "image"
              },
              "createdAt": "2023-06-16T14:21:36.761Z",
              "updatedAt": "2023-06-16T14:21:41.736Z"
            }
          }
        },
        "comments": {
          "data": [
            {
              "id": 1,
              "attributes": {
                "name": "Ritarpan Ghosh",
                "email_id": "ritarpanghosh29@gmail.com",
                "comment": "HELOO",
                "createdAt": "2023-06-17T11:59:50.333Z",
                "updatedAt": "2023-06-17T11:59:50.996Z",
                "publishedAt": "2023-06-17T11:59:50.987Z"
              }
            }
          ]
        }
      }
    }
  ],
  "meta": {
    "pagination": {
      "page": 1,
      "pageSize": 25,
      "pageCount": 1,
      "total": 1
    }
  }
}
lo8azlld

lo8azlld1#

您正在将blog对象传递给SubmitComment

<SubmitComment blog={blog} />

不需要解构博客上的参数,更改为

const SubmitComment = async (blog:any) => {

希望这对你有帮助

相关问题