类型错误:products.map不是nextjs中的函数

r3i60tvu  于 2023-01-20  发布在  其他
关注(0)|答案(2)|浏览(110)

我尝试在json文件中循环遍历产品,但一直收到此错误TypeError:www.example.com不是函数products.map is not a function**
这是我代码

import React from "react"; import Link from "next/link";

function shop({ products }) { return (
    <div>
      <nav>
        <Link href="/">Home</Link>
        <Link href="/shop">Shop</Link>
      </nav>
      <div className="title1">
        <h1>Explore All Products</h1>
      </div>
      <>
        {products.map((product) => { return (
            <div key={product.id}>
              <Link href="">
                <h2>
                  {product.id} {product.title}
                </h2>
              </Link>
            </div>
          );
        })}
      </>
    </div>   ); }

export default shop;

export async function getStaticProps() { const response = await fetch("https://dummyjson.com/products"); const data = await response.json(); console.log(data);

return { props: { products: data,
    },   }; }

我尝试了很多其他人对堆栈溢出的东西,没有任何工作

4ktjp1zp

4ktjp1zp1#

> import React from "react"; import Link from "next/link";
    > 
    > function shop({ products }) {   return (
    >     <div>
    >       <nav>
    >         <Link href="/">Home</Link>
    >         <Link href="/shop">Shop</Link>
    >       </nav>
    >       <div className="title1">
    >         <h1>Explore All Products</h1>
    >       </div>
    >       <>
    >         {products.map((product) => {
    >           return (
    >             <div key={product.id}>
    >               <Link href="">
    >                 <h2>
    >                   {product.id} {product.title}
    >                 </h2>
    >               </Link>
    >             </div>
    >           );
    >         })}
    >       </>
    >     </div>   ); }
    > 
    > export default shop;
    > 
    > export async function getStaticProps() {   const response = await
    > fetch("https://dummyjson.com/products");   if (response.status !==
    > 200){
    >     console.log(`Error: ${response.status}`);   }   const data = await response.json();
    >   
    > 
    >   return {
    >     props: {
    >         products: data.products, //instead of just "data"
    >     },   }; }
vq8itlhq

vq8itlhq2#

端点https://dummyjson.com/products返回如下对象:

{
    "products": [...],
    "total": 100,
    "skip": 0,
    "limit": 30
}

所需的数据位于products属性中,因此只需用途:

return { props: { products: data.products } };

相关问题