我有以下代码,它使用 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 转换为列和数据?
最佳答案
假设您的问题是如何呈现对象以匹配表数据对象中的键,类似这样的事情应该可以工作:
在这里回复: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>
);
}
}
```
关于javascript - 如何使用rest api中的antd table组件渲染datagrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51654039/