html - 表格没有在 Reactjs 中相应地显示数据
问题描述
我正在尝试将 API 的响应显示到 react-semantic-ui 表中。在设置了获取数据的状态后,我需要将一阶键作为列名,然后将二阶键作为行名,二阶键的值将显示在表体中。我已经做到了这一点,这导致每行中的单元格数量增加一倍,同时使用相同的数据设置所有单元格值。
class NonProtectedFeatureBias extends Component {
constructor(props){
super(props);
this.state = {
staticPostData:{
dataset_id: 1
},
tableData:{},
tableColumnNames:[],
};
}
renderKeys (data) {
let tcolumn = [];
for(let i=0; i<Object.keys(data).length;i++){
const Obj1 = Object.keys(data)[i];
//console.log(Obj1)
tcolumn.push(Obj1);
}
let col = tcolumn.map(item=>{
return <Table.HeaderCell>{item}</Table.HeaderCell>
})
return col
}
renderValues (data) {
let row=null;
for(let i=0; i<Object.keys(data).length;i++){
const Obj1 = Object.values(data)[i];
let trows = [];
const Obj2 = Object.keys(Obj1).map(item =>{
trows.push(item);
});
let tvalues =[];
const Obj3 = Object.values(Obj1).map(item =>{
tvalues.push(item);
console.log(item)
});
row = trows.map(item=>{
return(
<Table.Row className="cell-current">
<Table.Cell className="cell-width-single">{item}</Table.Cell>
{tvalues.map(val =>{
return <Table.Cell selectable>{val}</Table.Cell>
//console.log(val)
})}
</Table.Row>
)
})
}
return row
}
componentDidMount() {
this.fetchData();
}
fetchData(){
axios.post('http://localhost:5000/GetProxyTable', this.state.staticPostData)
.then((response) =>{
var count = Object.keys(response.data).length;
this.setState({tableData:response.data})
console.log(response.data)
});
}
render(){
return (
<Container style={{height:"250px", backgroundColor:""}}>
<Table definition >
<Table.Header>
<Table.Row className="cell-with-no-padding">
<Table.HeaderCell />
{this.renderKeys(this.state.tableData)}
</Table.Row>
</Table.Header>
<Table.Body>
{this.renderValues(this.state.tableData)}
</Table.Body>
</Table>
</Container>
);
}
}
export default NonProtectedFeatureBias;
这是我从 API 得到的响应
这是实现我的目标的正确方法吗?!我希望有一个优化的方法来做到这一点。而且我还需要能够单击一个单元格并获取相关的行和列名称。任何建议或意见将不胜感激。
解决方案
您renderValues
正在通过列而不是行进行映射。另外,您将每个假行设置为相同的值,因此所有“行”都是相等的。最后,返回最后一个,表示最后一列的值。
您可以尝试下面的代码,在呈现行之前先将列映射到行对象:
renderValues (data) {
const rows = {}
Object.values(data).forEach(col => {
for (let [key, value] of Object.entries(col)) {
rows[key] = rows[key] ? [...rows[key], value] : [value]
}
})
return Object.entries(rows).map(([item, values]) => (
<Table.Row className="cell-current">
<Table.Cell className="cell-width-single">{item}</Table.Cell>
{ values.map(val => <Table.Cell selectable>{val}</Table.Cell> ) }
</Table.Row>
))
}
推荐阅读
- excel - 如何替换没有样式的 Excel 工作表单元格的样式,然后为单元格添加值?
- php - Alpine 3.8 Docker 映像:在 libmongoc 上启用 SSL
- r - 如何将不重复的整数向量转换为多个连续和离散的部分,并使用 R 以特定格式导出?
- javascript - 检查是否有包含单词的频道?
- javascript - 如何处理 Oracle Apex 中的选项卡更改
- c# - 按小时范围分组 dateTime
- python-3.x - 在 Python 中参数化函数名称
- azure-devops - Azure Devops:在管道名称指令中使用时缩短 $(SourceBranchName)
- spring-cloud-contract - 讨论:基于 CDC 的生产者测试应该模拟业务逻辑还是与业务逻辑集成
- python - 无法使用 SimpleITK 读取 dicom