我无法弄清楚为什么服务器端道具在 nextjs (v12) 中对我不起作用 我在pages/details/index.tsx中使用getServerSideProps
export const getServerSideProps = (async (context: any) => {
const name = context.query.name;
const response = await fetchDetails(name);
const data = response.data;
console.log(data); // this line is printing details in server
return { props: { data } };
});
export default function Page({data}: {data: any) {
console.log('p', data);
return <DetailsForm data={data} name="abc"/>
}
虽然我可以获得 props.name 作为“abc”,但数据是未定义的。
您在 Next.js 应用程序中使用 getServerSideProps 函数的方式似乎可能存在问题。让我们看一下代码,看看能否找出问题所在。
首先,确保您的 fetchDetails 函数正常工作并返回预期的数据。
假设 fetchDetails 工作正常,让我们检查一下 getServerSideProps 函数。它似乎是立即调用的异步函数。虽然这种语法可以工作,但通常最好单独定义函数。这是更正后的代码:
export async function getServerSideProps(context: any) {
const name = context.query.name;
const response = await fetchDetails(name);
const data = response.data;
console.log(data); // this line is printing details in the server
return { props: { data } };
}
export default function Page({ data }: { data: any }) {
console.log('p', data);
return <DetailsForm data={data} name="abc" />;
}
通过将 getServerSideProps 定义为 IIFE(立即调用函数表达式)之外的异步函数,您应该能够正确检索数据并将其作为 prop 传递给您的 Page 组件。
如果您仍然遇到数据未定义的问题,请确保您的 fetchDetails 函数返回预期的数据,并仔细检查 Next.js 项目中的服务器端渲染设置。确保您已在应用程序中正确导入并配置 Next.js。
切克兄弟