我正在做一个亚马逊克隆next.js和fakestoreapi产品数据,但我无法接收数据到浏览器。但是它们接收到vscode控制台。我甚至没有得到任何错误信息。我的代码如下:
- index.js
import Head from "next/head";
import Header from "../src/Components/Header";
import Banner from "../src/Components/Banner";
import ProductFeed from "../src/Components/ProductFeed";
export default function Home({ products }) {
return (
<div>
<Head>
<title>ShopBag | amazon Clone</title>
</Head>
<Header />
<main className="max-w-screen-2xl bg-gray-100 mx-auto">
{/* banner */}
<Banner />
{/* product Feild */}
<ProductFeed products={products} />
</main>
</div>
);
}
export async function getServerSideProps(context) {
const products = await fetch("https://fakestoreapi.com/products")
.then((res) => res.json())
.then((json) => console.log(json));
return {
props: {
products: products || null,
},
};
}
ProductFeed.js
import React from "react"; import Product from "./Product"; function ProductFeed({ products }) { return ( <div> {products?.map(({ id, title, price, description, category, image }) => ( <Product key={id} title={title} price={price} description={description} category={category} image={image} /> ))} </div> ); } export default ProductFeed;
Product.js
import React from "import Image from "next/Image ">
function Product({ id, title, price, description, category, image }) { return ( <div> <p>{category}</p> <Image src={image} height={200} width={200} objectfit="contain" alt="product-images" /> </div> ); } export default Product;
next.config.js
/** @type {import('next').NextConfig} */
const isProd = process.env.NODE_ENV === "production";
const nextConfig = {
reactStrictMode: true,
Images: {
domains: ["./public", "fakestoreapi.com"],
assetPrefix: isProd ? "/amazon-clone/" : "",
},
};
module.exports = nextConfig;
这是因为你在第二个然后记录json,而不是返回它。你应该这样做:
....
.then(json => json)
或者如果你想记录它:
.then(json => {
console.log(json)
return json
})
你可以删除它并使用await
const response = await fetch("https://fakestoreapi.com/products");
const products = await response.json();
return {
props: {
products: products || null,
},
};