为啥 getServerSideProps 没有将正确的值传递给组件 props?
Posted
技术标签:
【中文标题】为啥 getServerSideProps 没有将正确的值传递给组件 props?【英文标题】:Why does getServerSideProps doesn't pass the right value to the component props?为什么 getServerSideProps 没有将正确的值传递给组件 props? 【发布时间】:2021-04-21 16:16:02 【问题描述】:我正在尝试从 4 个不同的端点获取数据并使用 getServerSideProps (Next.js) 将它们作为道具传递,但尽管从 getServerSideProps 返回的“课程”变量确实包含所需的课程,但参数组件接收到的 courses 结果是一个空数组 ([])
import axios from 'axios'
import React from 'react'
import Courses from '../../components/career/Courses'
import JobExperiences from '../../components/career/JobExperiences'
import University from '../../components/career/University'
import Layout from '../../components/ui/Layout'
import SectionDescription from '../../components/ui/SectionDescription'
import Course from '../../data/interfaces/career/Course'
import useTranslation from '../../hooks/useTranslation'
interface CareerProps
courses: Course[]
const Career = ( courses : CareerProps) =>
const t = useTranslation();
return (
<Layout title="Career">
<section className="p-5 sm:p-8 md:p-16 lg:p-32">
<header>
<SectionDescription title=t.career.title description=t.career.description />
</header>
<JobExperiences />
<University />
<Courses courses=courses />
</section>
</Layout>
)
export async function getServerSideProps()
const courses: Course[] = []
const courseIDs = [
"1362070",
"3096364",
"947098",
"1879018",
]
courseIDs.forEach(async courseID =>
const data = await axios.get(`https://www.udemy.com/api-2.0/courses/$courseID/`);
courses.push(data)
)
return
props: courses: courses ,
export default Career
【问题讨论】:
forEach
不会等待承诺得到解决,即使您使用的是异步等待
【参考方案1】:
尝试将 API 调用替换为以下内容,因为 forEach
无法按预期处理 async-await
调用:
await Promise.all(
courseIDs.map(async (courseID) =>
const data = await axios.get(`https://www.udemy.com/api-2.0/courses/$courseID/`);
courses.push(data);
)
);
【讨论】:
以上是关于为啥 getServerSideProps 没有将正确的值传递给组件 props?的主要内容,如果未能解决你的问题,请参考以下文章
为啥 NextJS 中的 ApolloGraphQL 示例使用 getStaticProps 而不是 getServerSideProps
Next.js - 页面没有让 GetServerSideProps 进入页面组件道具(使用自定义 _app.js)
NextJS getServerSideProps() 具有多个获取请求