首页 > 解决方案 > 如何使用来自rest api的antd表组件渲染数据网格

问题描述

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

在此处输入图像描述

代码:

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 转换为列和数据?

标签: javascriptjsonreactjsantd

解决方案


假设您的问题是如何渲染对象以匹配 Table 数据对象中的键,这样的事情应该可以工作:

在此处复制:https ://repl.it/repls/FabulousWiryLicensing

这将为您提供想法,但更简洁的解决方案是映射responseJson您从 API 调用中返回的对象并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>
    );
  }
}

```


推荐阅读