reactjs - 通过数组和 API 调用进行异步映射时如何在 React 中设置状态
问题描述
我正在尝试在 React 中通过我的状态(收藏夹)映射()以从状态中的每个条目中获取数据。数据应存储在另一种状态、股票中,并显示在表格中。
Map() 通过状态和获取数据工作,我可以在控制台日志中看到日期。但它不会存储在状态中。
如何将数据添加到状态?
这是代码:
// Calling the function on component mount
useEffect(() => {
tableFetch();
}, []);
const [favorites, setFavorites] = useState(["aapl", "arlv"]);
const [stocks, setStocks] = useState([]);
// fetch symbol data and stores it in stocks
const tableFetch = () => {
favorites.map( async (favorites) => {
const data = await fetch(
`https://cloud.iexapis.com/stable/stock/${favorites}/quote?token=${token}`
);
const stocksData = await data.json();
console.log(stocksData)
setStocks(stocksData);
});
}
解决方案
这里有几个问题。
- 当您在收到响应后进行 API 调用时,状态将被新数据覆盖,或者可能会发出范围可用性
建议: 2. 你为什么不进行多次API调用,当它们解决时,收集所有信息然后setState。
useEffect(() => {
tableFetch();
}, []);
const tableFetch = async () => {
// Note: the below code will create urls & make parallel calls
let axiosFetch = favorites.reduce((axiosCalls, url) => {
axiosCalls.push(axios.get(`https://reqres.in/api/users?page=${url}`));
return axiosCalls;
}, []);
// Here promises will settle and will collect all the data.
await axios
.all(axiosFetch)
.then((data) => {
let dataCollected = data.reduce((dataCollected, response) => {
dataCollected = dataCollected.concat(response.data.data);
return dataCollected;
}, []);
// After collecting all the data we can set data into state at once.
setStocks(dataCollected);
})
.catch((error) => {
console.log("collect errors", error);
});
};
注意:我使用的是 Axios 库,同样的事情也可以使用 fetch 完成。
推荐阅读
- rest - 使用 com.sun.jersey.api.client.WebResource 创建 URI 时出错,将字符串值添加到路径
- android - 如何下载具有所有依赖项的工件?
- mysql - Mysql选择查询不在同一张表中
- python-3.x - 科学记数法在python中作为数字(不是字符串)
- ruby - Mongoid - 在 belongs_to 关系的查找/连接中替换数组的第一个元素
- javascript - Epic App Orchard 如何获取从业者 ID 或信息
- http - 如何 AWS 将负载均衡器从 HTTP 路由到 TOMCAT 服务器的 HTTPS
- python - 如何对熊猫数据框行执行卡方测试?
- highcharts - Firefox / IE 将日期格式化为 1970
- javascript - 根据文本调整 Bootstrap 手风琴按钮高度