下一个 JS [id] 错误 序列化".data"时出错,从 "/services/[id]" 中的"getServerSideProps"返回



我做Next JS项目,我是新编码在这个程序,并有一个"服务"文件夹中。在这个文件夹中有index.js和[id].js(详情页)。所有数据都来自Next API。Index.js工作,没有问题。但是,当我单击details元素时,会看到错误。我不知道我错在哪里

Error: Error serializing `.data` returned from `getServerSideProps` in "/services/[id]". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.

index.js

<section className="services-main">
<div className="services-main-context container">
<MainPageServices posts={posts} />
</div>
</section>
....
export async function getStaticProps() {
const res = await fetch("http://localhost:3000/api/servicesApi/");
const posts = await res.json();
return {
props: {
posts,
},
};
}

MainPageServices组件

<div className="main-page-services-cards">
{posts.map((card, key) => (
<div key={card.id} className="service-card">
<Link href={`/services/${card.id}`}>
<a>
<div className="card-img">
<Image src={card.img} alt="Services" />
</div>
</a>
</Link>
</div>
))}
</div>

不工作组件(Details)

const ServiceDetails = ({ data }) => {

console.log(data);
return (
<h1>{data.header}</h1>)  
);
};

export const getServerSideProps = async (context) => {
const res = await fetch(`http://localhost:3000/api/servicesApi/${context.params.id}`);
const data = res.json();
return {
props: {
data,
},
};
};

My details page API

import { servicesData } from "../../../data";
export default function handler(req, res) {
const { id } = req.query;
const service = servicesData.find((service) => service.id === parseInt(id));
res.status(200).json(service);
}

我认为你需要等待res.json(),因为你的错误说你正在传递一个承诺到你的道具

const ServiceDetails = ({ data }) => {

console.log(data);
return (
<h1>{data.header}</h1>)  
);
};

export const getServerSideProps = async (context) => {
const res = await fetch(`http://localhost:3000/api/servicesApi/${context.params.id}`);
const data = await res.json();
return {
props: {
data,
},
};
};

相关内容

  • 没有找到相关文章

最新更新