【发布时间】:2021-02-14 10:30:39
【问题描述】:
我正在使用 nextJs 并且有 1 页 - index.js 和一个我要导入到 index.js 的组件,名为 Products。 Products 包含对我从中获取数据的 graphql 端点的请求。
我在products.map 上收到错误 fCannot read property 'map' of undefined,因为我认为它没有执行获取请求。
Products组件挂载到index.js时如何执行请求?
(如果我直接粘贴到index.js 文件中,Products 中的代码有效)
index.js
import Link from 'next/link';
import Products from '../components/Products'
const Layout = () => {
return(
<div>
<Products />
</div>
)
}
export default Layout
products.js
import Link from "next/link";
import { GraphQLClient } from "graphql-request";
export async function getStaticProps() {
const graphcms = new GraphQLClient(
"https://api-eu-central-1.graphcms.com/v2/ckbmb39xb04eo01wh7yc80q8m/master"
);
const { products } = await graphcms.request(
`
{
products {
slug
name
}
}
`
);
return {
props: {
products
}
};
}
export default ({ products }) =>
products.map(({ slug, name }) => (
<Link key={slug} href={`/products/${slug}`}>
<a>{name}</a>
</Link>
));
【问题讨论】:
标签: next.js