为什么 getServerSideProps 没有将正确的值传递给组件 props?

时间:2021-01-17 01:08:41

标签: reactjs typescript next.js getserversideprops

我正在尝试从 4 个不同的端点获取数据并将它们作为道具传递给 getServerSideProps (Next.js) 但尽管从 getServerSideProps 返回的“courses”变量确实包含所需的课程,参数组件接收到的 {course} 原来是一个空数组 ([])

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

1 个答案:

答案 0 :(得分:2)

尝试将 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);
    })
);