如何将数据从GraphQL服务器显示到npm react-table?

时间:2018-01-09 10:37:03

标签: reactjs graphql react-apollo react-table

我一直在开始使用GraphQL serverApollo client。代码用Reactjs编写。现在我想使用任何查询从GraphQL服务器获取数据,并在UI中向表中显示数据。我使用npm react-table表。

The table could look like this:

如果查询响应没有数组,我可以轻松获取并显示数据。例如,我有下面的查询输入字符串:

{
  account {
    firstName
    lastName
    id
  }
}

查询结果没有数组

{
  "data": {
    "account": {
      "firstName": "Marlen",
      "lastName": "Marquardt",
      "id": 2
    }
  }
}

在ReactTable组件中,我只使用data.account.firstName

获取数据
<ReactTable
  data={[
    {
      firstName: data.account.firstName,
      lastName: data.account.lastName,
      id: data.account.id,
    }
  ]}
  columns={columns}
/>

但是,如果查询结果有数组,我就不知道如何获取数据。请看一下图片 query result with array

那么如何向桌子展示所有5个玩具title? 这是我的旧代码:

import React from 'react';
import s from './Test.css';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import fetch from 'node-fetch';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import ReactTable from 'react-table'
import 'react-table/react-table.css';

const localURL = 'http://localhost:3000/graphql';
const client = new ApolloClient({
  link: new HttpLink({ uri: localURL, fetch }),
  cache: new InMemoryCache()
});
const columns = [
  {
    Header: "ID",
    accessor: "id"
  },
  {
    Header: "First Name",
    accessor: "firstName"
  },
  {
    Header: "Last Name",
    accessor: "lastName"
  }
]

class Table extends React.Component {
  render() {
    let { data } = this.props;
    return (
      <div>
        <h2> ADMIN </h2>
        <ReactTable
          data={[
            {
              firstName: data.account.firstName,
              lastName: data.account.lastName,
              id: data.account.id,
            }
          ]}
          columns={columns}
          defaultPageSize={10}
        />
      </div>
    );
  }
}

const queryAccountList = gql`
  query {
    account{
      firstName
      lastName
      id
      }
    }
  }
`

const AccountListWithData = graphql(queryAccountList)(Table);

export default AccountListWithData;

1 个答案:

答案 0 :(得分:1)

正如您所看到的,您的ReactTable的数据支持需要一个数组(或者至少,在您的示例中,您传递的是一个包含1个对象的数组)。

另请注意,GraphQL返回的数据对象的格式为

  {
    account
    {
      firstName,
      lastName,
      id
    }
  }

因此,您可以使用data={[ data.account ]}定义具有相同结果的ReactTable数据。

现在假设你执行了玩具查询,然后返回的数据将是

形式
{
  allToy [
    {
      id,
      title
    },
    {
      id,
      title
    },
    ...
  ]
}

因此,如果您的数据定义保持不变(const { data } = this.props;),则data.allToy将是{ id, title }个对象的数组。

因此,您可以将Toy ReactTable定义为:

<ReactTable
  data={ data.allToy }
  columns={columns}
  defaultPageSize={10}
/>