我正在尝试进行后续的API调用,以获取有关某些财务指数的信息。。每次调用后,我都想更新de-indexObject,使其拥有我存储在索引数组中的所有索引的所有数据。问题是,每次调用setIndexObject时,它都会覆盖对象,即使我使用排列运算符,也会丢失以前的值。
const [indexObject, setIndexObject] = useState({});
const indexes = [
"^GDAXI",
"^BVSP",
"^NDX",
"^DJI",
"^GSPC",
"^IBEX",
"^HSI",
"^BSESN",
"^FTSE",
];
useEffect(() => {
indexes.forEach((index) => {
const options = {
method: "GET",
url:
"https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-summary",
params: { symbol: `${index}`, region: "US" },
headers: {
"x-rapidapi-key":
"----",
"x-rapidapi-host": "apidojo-yahoo-finance-v1.p.rapidapi.com",
},
};
axios
.request(options)
.then(function (response) {
setIndexObject({
...indexObject,
[index]: {
value: response.data.price.regularMarketPrice.fmt,
variation: response.data.price.regularMarketChangePercent.fmt,
},
});
})
.catch(function (error) {
console.error(error);
});
});
}, []);
这就是我正在努力实现的目标:
{
A:{
value:,
variation:,
},
B:{
value:,
variation,
}
}
谢谢你的帮助!
这里的问题是循环请求,而setState
不是同步的。最好先填充所有数据,然后再设置状态。
const [indexObject, setIndexObject] = useState({});
const handleFetchData = async () => {
const indexes = [
"^GDAXI",
"^BVSP",
"^NDX",
"^DJI",
"^GSPC",
"^IBEX",
"^HSI",
"^BSESN",
"^FTSE",
];
const resultData = {};
for(const index of index) {
const response = await axios.request(); // add your own request here
resultData[index] = response;
}
return resultData;
}
useEffect(() => {
handleFetchData().then(data => setIndexObject(data));
}, []);
为什么我使用for of
?因为CCD_ 3或CCD_。或者,如果您想同时获取所有数据,可以考虑使用Promise.all