通过多个 Axios 调用异步加载数据
我有一堆图表要显示,需要为每个图表单独加载数据。
标识每个图表的数据结构是数组,如下所示(子数组可以容纳一个或多个图表。如果子数组中有多个项目,图表将具有多个轴):
"charts":[["chart1"], ["chart2", "chart4", ...], ...]
事先不知道有多少项目将在子数组中数组以及它们将有多少子项。
我的方法
首先,我浏览图表
并显示占位符(加载器),然后如果数据
状态可用,则显示图表:
const[data, setData] = useState(null);
return(
charts.map(item => {
(item in data && data[item] !== "") ? <Chart data={data[item]} /> : <Loader />
})
)
对于>Axios
数据获取我想使用 useEffect
来填充 data
状态变量,然后重新渲染组件以显示已加载的图表。
我的问题是,我不确定如何利用 useEffect
来执行此操作,即在循环中调用 Axios
并在中设置 data
状态变量循环对我来说似乎不合适。我猜它会创建无限循环。
另一个较小的问题是,如何等待所有子项的数据加载以显示多轴图表(如果适用)。
I have a bunch of charts to display and need to load data separately for each of them.
The data structure identifying each chart is array and looks like this (subarray can host one or more charts. In case of multiple items in subarray, the chart will have multiple axis):
"charts":[["chart1"], ["chart2", "chart4", ...], ...]
There is not known in advance how many items will be in the array and how much they will have subitems.
My approach
First I go through charts
and display placeholders (loaders), then if data
state is available, display the chart:
const[data, setData] = useState(null);
return(
charts.map(item => {
(item in data && data[item] !== "") ? <Chart data={data[item]} /> : <Loader />
})
)
For the Axios
data fetch I thought to use useEffect
which would fill the data
state variable, which would then re-render the component to show already loaded charts.
My issue here is, that I am not sure how to utilise useEffect
to do this as calling Axios
in a loop and setting data
state variable in a loop does not seem right to me. I guess it would then create infinite loop.
The other a bit smaller question is, how to wait for data load of all subitems to display multiaxis chart, if it applies.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据评论,下面是一个使用来自多个 api 调用对不同端点的响应来更新 useEffect 挂钩中的 setData 的示例:
Based off the comments, here is an example of updating setData in a useEffect hook with the responses from multiple api calls to different endpoints: