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

问题描述

我正在尝试从 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

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...