0

我正在使用 GraphQL 和 Shopify 的 Polaris 组件CardDataTable构建一个 Shopify 应用程序。因此,由于平台依赖性,生成一个最小的、可重现的示例是一个相当大的挑战。

该组件产生预期的结果:

import React from 'react';
import { Card, DataTable, } from '@shopify/polaris';

function vendorData() {
  return [["a", 1],["b", 3],["c", 2]]
}

export default function Vendors() {
  const rows = vendorData()
  return (
      <Card>
        <DataTable
            columnContentTypes={[
              'text',
              'numeric',
            ]}
            headings={[
              'Vendor',
              'Count',
            ]}
            rows={rows}
          />
      </Card>
  );
}

在此处输入图像描述

插入 GraphQL 部分后,我的组件如下所示:

import React from 'react';
import { Card, DataTable, } from '@shopify/polaris';
import { gql, useQuery } from '@apollo/client';

const GET_PRODUCTS = gql`
  query ProductsVendors ($cursor: String) {
    products(first:80, after: $cursor) {
      edges {
        node {
          id
          vendor
          productType
        }
        cursor
      }
      pageInfo {
        hasNextPage
      }
    }
  }`; 


function vendorData() {
  /* submit the GraphQL query to Shopify
  return a list like [["vendor_a", 1],["vendor_b", 3],["vendor_c", 2]] 
  required by the Shopify DataTable component */

  const { loading, error, data } = useQuery(GET_PRODUCTS);
  if (loading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>

  const vendors = data.products.edges.map((el) => el.node.vendor )
  const vendorCounts = vendors.reduce((acc, curr) => 
    (acc[curr] = (acc[curr] || 0) + 1, acc), {});
  // vendorCounts is list of dicts, return it as list of lists
  return Object.keys(vendorCounts).map((key) => [key, vendorCounts[key]]);
}

export default function Vendors() {
  const rows = vendorData()
  console.log(rows);

  return (
      <Card>
        <DataTable
            columnContentTypes={[
              'text',
              'numeric',
            ]}
            headings={[
              'Vendor',
              'Count',
            ]}
            rows={rows}
          />
      </Card>
  );
}

但我得到了错误:

Server Error
TypeError: rows.map is not a function
This error happened while generating the page. 

然后当我通过字符串替换 DataTable 组件时

export default function Vendors() {
  const rows = vendorData()
  console.log(rows);

  return (
      <Card>
        Hello world
      </Card>
  );
}

并保存,组件已构建: 在此处输入图像描述

然后,当我使用 GraphQL 查询回滚到以前的版本时,组件已正确构建: 在此处输入图像描述

似乎该rows变量并不总是可用。知道是什么导致了这个问题吗?

4

0 回答 0