简体   繁体   English

从多个组件调用的多个 axios 请求中检索状态

[英]Retrieve the status from multiple axios requests called from multiple components

I have a sort of Dashboard in my application.我的应用程序中有一种仪表板。 In this dashboard I let the user put many widgets (each widget is a class component).在这个仪表板中,我让用户放置了许多小部件(每个小部件都是一个 class 组件)。 Each widget renders different stuff, such as, charts, images, and text.每个小部件呈现不同的内容,例如图表、图像和文本。 When I display it, each widget make an axios call to retrieve data from backend.当我显示它时,每个小部件都会调用 axios 来从后端检索数据。 I need a way to be able to tell when all the requests have finished so I can get the HTML completely rendered (I'm going to export it using HiqPdf later).我需要一种能够判断所有请求何时完成的方法,以便我可以完全渲染 HTML(稍后我将使用 HiqPdf 导出它)。

I need each widget to be independent so I can use in other components.我需要每个小部件都是独立的,以便我可以在其他组件中使用。 That's why each widget make its own axios call.这就是为什么每个小部件都有自己的 axios 调用。 Otherwise I think I could make many axios calls in a single component that is above my widgets and then I would pass all the data as props to each widget.否则,我认为我可以在我的小部件上方的单个组件中进行许多 axios 调用,然后我会将所有数据作为道具传递给每个小部件。 However, no... the axios calls must stay inside each widget.但是,不... axios 调用必须保留在每个小部件内。 I've found many places talking about promises, but every example talks show how to do it in a single component.我发现很多地方都在谈论 Promise,但每个示例都展示了如何在单个组件中做到这一点。

The reason I'm working on it is because I have the need to export it using a library call HiqPdf.我正在研究它的原因是因为我需要使用一个名为 HiqPdf 的库来导出它。 This library receives a HTML as string and exports to PDF.该库接收 HTML 作为字符串并导出到 PDF。 Therefore, I need to know when the dashboard has been completely loaded to let the application export it.因此,我需要知道仪表板何时已完全加载以让应用程序导出它。

Think about an event-driven framework that persists the global state of your single page app and notify subscribers whenever there is a change in the state.考虑一个事件驱动的框架,它可以持久保存单页应用程序的全局 state ,并在 state 发生更改时通知订阅者。

One of the famous frameworks is .著名的框架之一是

Another simple framework is .另一个简单的框架是 These are some similar questions that leverages :这些是利用的一些类似问题:

For your case, it might be something like this:对于您的情况,可能是这样的:

const all_calls = [];
const {on, one, fire, unsub} = mufa;

axios.get('call1').then((data) => {

   fire('call1_received', data);
})


axios.get('call2').then((data) => {

   fire('call2_received', data);
});


one('call1_received', () => {
  all_calls.push('call1_received');
  if (all_calls.length === 2) {
     alert('!!!! All calls have been received')
  }

})

one('call2_received', () => {
  all_calls.push('call2_received');
  if (all_calls.length === 2) {
     alert('!!!! All calls have been received')
  }

})

Note, one will subscribe once only.. while on subscribe forever.请注意, one只会订阅一次...... on永远订阅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM