我一直在使用GraphQL server
and Apollo client
。代码是用Reactjs
. 现在我想使用任何查询从 GraphQL 服务器获取数据,并将数据显示到 UI 中的表中。我使用 npmreact-table
作为表。
如果查询响应没有数组,我可以轻松获取并显示数据。例如,我有下面的查询输入字符串:
{
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}
/>
但是,如果查询结果有数组,我不知道如何获取数据。请看 带数组的图片查询结果
那么我怎样才能把所有 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;