如何从Rest API使用Antd Table组件呈现DataGrid

时间:2018-08-02 12:45:45

标签: javascript json reactjs antd

我有以下代码,该代码呈现带有antd组件的表。 我创建了一个fetchdata,可以正确返回一些信息

enter image description here

代码:

import React, { Component } from 'react';
import {  Table} from 'antd';
import { adalApiFetch } from '../../adalConfig';


class ListTenants extends Component {

    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }

    fetchData = () => {
        adalApiFetch(fetch, "/Tenant", {})
          .then(response => response.json())
          .then(responseJson => {
            if (!this.isCancelled) {
              this.setState({ data: responseJson });
            }
          })
          .catch(error => {
            console.error(error);
          });
      };


    componentDidMount(){
        this.fetchData();
    }

    render() {
        const columns = [{
            title: 'Tenant Id',
            dataIndex: 'TenantId',
            key: 'TenantId'
          }, {
            title: 'Tenant Url',
            dataIndex: 'TenantUrl',
            key: 'TenantUrl',
        }];

        const data = [{
            TenantId: '1',
            TenantUrl: 'John Brown'           
          }, {
            TenantId: '2',
            TenantUrl: 'Jim Green'
          }, {
            TenantId: '3',
            TenantUrl: 'Joe Black'
        }];

        return (
            <Table columns={columns} dataSource={data} />
        );
    }
}

export default ListTenants;

如何将接收到的json转换为列和数据?

1 个答案:

答案 0 :(得分:1)

假设您的问题是如何呈现对象以匹配Table数据对象中的键,则应该可以执行以下操作:

在这里表示:https://repl.it/repls/FabulousWiryLicensing

这将为您提供一个想法,但是更干净的解决方案是将您从API调用中返回的responseJson对象映射到setState上。

```

 class App extends Component {
  constructor (props) {
    super (props)
    this.state = {
      returnedData: [{
        ClientId: '1',
        Id: 'abc',
        TenantDomainUrl: 'https://example.com'
      }, {
        ClientId: '2',
        Id: 'abc',
        TenantDomainUrl: 'https:example2.com'
      }]
    }
  }
  render() {
    const { returnedData } = this.state;

    const data = returnedData.map(row => ({
      TenantId: row.Id,
      TenantUrl: row.TenantDomainUrl
    }))

    const columns = [{
        title: 'Tenant Id',
        dataIndex: 'TenantId',
        key: 'TenantId'
      }, {
        title: 'Tenant Url',
        dataIndex: 'TenantUrl',
        key: 'TenantUrl',
    }];

    return (
      <div>
        <h1>test</h1>
        <Table columns={columns} dataSource={data} />
      </div>
    );
  }
}

```

相关问题