【问题标题】:nextjs mounted component not fetching datanextjs 安装的组件没有获取数据
【发布时间】: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


    【解决方案1】:

    getStaticPath 只能从页面i.e index.js 调用,因此您需要将export getStaticProps 移动到index.js 并将产品作为道具传递给您的products.js 组件。

    或者,如果您想在客户端获取数据,您可以在产品组件中使用 useEffect 挂钩

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2021-04-10
      • 2018-11-21
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多