【发布时间】:2021-09-12 11:32:29
【问题描述】:
我是第一次使用 nextjs 和 apollo,我只是想使用 .map 来迭代数据库结果。
这是我的组件代码:
import { gql, useQuery } from "@apollo/client"
import Link from "next/link"
import ErrorMessage from "../layout/ErrorMessage"
export const ALL_COURSES_QUERY = gql`
query getCourses($limit: Int, $field: String!, $order: Order!) {
courses(limit: $limit, sort: { field: $field, order: $order }) {
courseFeed {
id
title
videos {
title
}
creator {
id
lastName
}
sections {
title
}
ratings {
id
}
deletedAt
}
pageInfoCourse {
nextPageCursor
hasNextPage
}
}
}
`
export const allCoursesQueryVars = {
limit: 10,
field: "title",
order: "ASC",
}
export default function CourseList() {
const { loading, error, data } = useQuery(ALL_COURSES_QUERY, {
variables: allCoursesQueryVars,
})
if (error) return <ErrorMessage message="Error loading courses." />
const { courses } = data
console.log(courses) // see output below
return (
<section>
<ul>
{courses.map((course) => ( // this does not work
<li key={course.id}>
<Link
href={{
pathname: "/courses/[slug]",
query: { slug: course.slug },
}}>
<a>{course.title}</a>
</Link>
<p>{course.creator}</p>
</li>
))}
</ul>
</section>
)
}
控制台输出
{
__typename: 'CourseFeed',
courseFeed: [
{
__typename: 'Course',
id: '607c1f1201509f26b866cbba',
title: 'Kurs Eins',
videos: [Array],
creator: [Object],
sections: [Array],
ratings: [Array],
deletedAt: null
}
],
pageInfoCourse: {
__typename: 'PageInfoCourse',
nextPageCursor: null,
hasNextPage: false
}
}
错误信息
TypeError:courses.map 不是函数
我想遍历courseFeed 数组以使用我页面中的课程对象。我会非常感谢任何形式的帮助!
【问题讨论】:
标签: javascript arrays next.js javascript-objects