使用Promise.all的多个API调用可在控制台中显示结果,但与State一起发布



我正在react中进行多个API调用,我能够在控制台中完美地获取数据。但当我试图设置状态以便在UI中也显示时,它不起作用。根据我的分析,将数据设置为状态有问题。

这是我的密码。

import React, { Component } from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
const data = [
{
id: "IT58A2158"
},
{
id: "ITD856741"
},
{
id: "IT85TKACQ"
}
];

class Actions extends Component {
constructor(props) {
super(props);
this.state = {
Ids: []
};
}
componentDidMount() {
const headers = {
"Content-Type": "application/json",
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
Authorization: "Bearer 000000-0000-0000",
};
console.time('.map()')
Promise.all(
data.map(id => {
return new Promise((resolve) => {
fetch(`https://example.com/api/Item/${id.ID}?realm=xyz`, { headers })
.then(response => {
return new Promise(() => {
response.json()
.then(response => {
this.setState({Ids: response.data}); // I am trying here to set all data to State
console.log(response);
resolve()
})
})
})
})
})
)
.then((res) => {
console.timeEnd('.map()');
})
}
render() {
const { Ids } = this.state;
if (!Ids) {
return <h1>Please Wait....</h1>
}
return (
<div className="container-fluid" style={{ backgroundColor: '#f7f7f7' }}>
<table id="table-to-xls" className="table table-responsive table-striped display nowrap"  >
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Date</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody> 
{/* wants to render data here but not working */}
{Ids.map((record) => (
<tr>
<td>{record.id}</td>
<td>{record.dueDate}</td>
<td>{record.title}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default Actions;

感谢您的支持:-(

看起来您正在为每个API调用的单个响应数据设置一个新值Ids。是否应该将该值添加到Ids数组中?

this.setState((prevState) => ({
Ids: [...prevState.Ids, response.data]
}));

最新更新