从api获取数据后的状态变化。我可以通过 console.log() 看到这一点
但不会在更新后呈现数据。有我的代码获取代码:
useEffect(() => {
axios
.get(
'https://mylink.ngrok.io/channels/getUser',
).then((data)=>{
let array = [];
const promises = data.data.channels.map((channel)=>{
axios.get(`https://mylink.ngrok.io/channels/getChannel/${channel}`).then((resp)=>{
array.push(resp.data);
})
})
Promise.all(promises).then(()=>{
setonLineChannels(array);
});
})
}, []);
顺便说一下,它在上下文中。
我认为 Promise.all 原因是
谢谢
答案 0 :(得分:0)
在您声明 promises
的地方,它不会等待这些 API 请求完成。它们甚至在您调用 Promise.all(promises)
之前就已开始运行。
您可以将您定义为 promises
的代码直接放在 Promise.all()
中,然后确保在其中返回 get 请求。并且不要推送到 array
。您的地图将返回一个 promise 数组,您可以使用 .then
之后的 Promise.all
中的结果数组直接更新您的状态。
我的意思是:
useEffect(() => {
axios.get("https://mylink.ngrok.io/channels/getUser").then((data) => {
Promise.all(
data.data.channels.map(
(channel) =>
axios
.get(`https://mylink.ngrok.io/channels/getChannel/${channel}`)
.catch((err) => console.error(err)) // this allows an individual request to fail
)
).then((results) => setonLineChannels(results));
});
}, []);