【发布时间】:2021-07-17 15:32:24
【问题描述】:
我正在为我的应用程序使用 React,我正在从位于 http://localhost:8080/api/suppliers/supplier/list 的 API 获取数据
这是我的代码:
class SupplierData {
constructor(props){
super(props);
this.state = {
supplier: [
{
id: 0,
supplierTitle: "Supplier Title",
supplierFirstName: "First Name",
supplierLastName: "Last Name"
},
],
errorMessage: [],
};
}
ListAllSuppliers = async () =>{
return await axios.get(`http://localhost:8080/api/suppliers/supplier/list`)
.then((response) =>{
let apiResults = response.data;
this.setState({supplier: apiResults});
}).catch((error) =>{
this.setState({errorMessage: this.state.errorMessage.push(error)});
});
}
render(){
const TableRow = () => {
let {id, supplierTitle, supplierFirstName, supplierLastName} = this.state.supplier;
return (
<tr>
<td>
{this.state.supplier.map((i) => <p>{i.id}</p>)}
</td>
<td>
<span className="fw-normal">
{this.state.supplier.map((i) => <p>{i.supplierTitle}</p>)}
</span>
</td>
<td>
<span className="fw-normal">
{this.state.supplier.map((i) => <p>{i.supplierFirstName}</p>)}
</span>
</td>
<td>
<span className="fw-normal">
{this.state.supplier.map((i) => <p>{i.supplierLastName}</p>)}
</span>
</td>
);
};
return(
<table>
<thead>
.....
</thead>
<tbody>
{this.state.supplier.map((t, id) => <TableRow key={id}> {t} </TableRow>)}
</tbody>
</table>
);
}
场景
使用上面的代码,我将获取的数据全部放在一行中。
我希望将数据分布在各行中。 如果我从 API 获取 3 个对象,我希望每个对象都排成一行。 我目前有 3 行,但提取的 3 个对象在 1 行中。
如果我没有任何类似的行:
{this.state.supplier.map((i) => <p>{i.supplierLastName}</p>)}
我根本没有得到显示的数据。
我的问题:
如果我从 API 中获取了 3 个对象,我希望每个对象都排成一行,而不是将它们全部 3 个排成一行?
【问题讨论】:
-
我在 TableRow 组件中没有看到结束标记
-
在另一个组件渲染函数中定义一个组件有点奇怪...我建议你在SupplierData之外定义TableRow。这可能有助于了解您的数据发生了什么。目前我不确定你为什么要循环遍历主表中的供应商数据,还要在每个单元格中?
标签: javascript node.js reactjs axios react-hooks