javascript - 如何使用来自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 转换为列和数据?
解决方案
假设您的问题是如何渲染对象以匹配 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>
);
}
}
```
推荐阅读
- regex - 正则表达式用单个字符替换多次出现的字符
- python-3.x - Python。简单的计算器。从字符串中抓取算术运算符
- python - pytest repeat - 获取当前迭代次数
- r - 如何用另一张纸上的实际基因名称信息替换 DESeq2 rlogTransformation 矩阵中的行名?
- python - 2021 年 9 月 13 日 Google Drive API 更新如何影响使用 pydrive 进行身份验证
- c# - 在 DataGridView 中搜索,如何在过滤后的行中进行过滤
- android - 如何在 android 上以低延迟播放 RTSP 流?
- node.js - 将请求 localhost3000 代理到 http://localhost:5000/ 时发生错误 [ECONNREFUSED]
- react-native - React Native useState 性能问题
- arrays - 如何防止 arrayformula 填充空行(Google Sheets/Excel)