【问题标题】:Multiple fetch requests with setState in React and pie chart在 React 和饼图中使用 setState 的多个获取请求
【发布时间】:2019-10-25 01:31:52
【问题描述】:

我的查询执行时间超过 2 分钟,因此它在浏览器中超时。所以现在我已经中断了查询,现在作为一个单独的 API 运行,这很有帮助,但现在我不知道如何处理这三个请求以便它可以呈现数据。

注意:API 的数据存储在 react 的 State 组件中,这里是“Data”。

现在我有了一个逻辑,但谁能给我一个如何实现它的方向。

逻辑:在将API的结果直接存入状态组件之前,我们可以将其存入不同的数组中,然后我们可以遍历这个数组以供饼图使用,然后这些数据可以存入状态组件中,可以用于在“渲染”函数中渲染饼图。

这里我同时进行三个不同的API调用并存储,这里API的结果直接存储在状态组件中:

componentDidMount() {
    Promise.all([
      fetch("http://localhost:4000/api/EMEA/E_claimQuarter"),
      fetch("http://localhost:4000/api/EMEA/E_claimQuarter1"),
      fetch("http://localhost:4000/api/EMEA/E_claimQuarter2")
    ])
      .then(([res1, res2, res3]) => 

      Promise.all([res1.json(), res2.json(), res3.json()]))

      .then(([data1, data2, data3]) => 

        this.setState({
          // Data: data1, data2, data3,
          Data: {
            labels: [
              "FY19 Q1[NOV-JAN]",
              "FY19 Q2[FEB-APR]",
              "FY18 Q3[SEP-NOV]"
            ],
            datasets: [
              {
                label: "",
                data: data1,
                backgroundColor: [
                  "rgba(255,105,145,0.6)",
                  "rgba(155,100,210,0.6)",
                  "rgb(63, 191, 191)"
                ]
              }
            ]
          }
        })
      );
  }

这就是您处理数据表单 API 并遍历它的方式,然后为各种图表呈现这些数据,在我的例子中是饼图:

ComponentDidMount() {
    axios.get(`http://localhost:4000/api/APJ/A_claimQuarter`)
***************************************************************
    .then(res => {
          const claims = res.data;
          let claim = [];

          claims.forEach(element => {
            claim.push(element.CNT1);

          });
********************************************************************
          this.setState({ 
            Data: {
              labels: ['FY19 Q1[NOV-JAN]','FY19 Q2[FEB-APR]','FY18[SEP-NOV]'],
              datasets:[
                 {
                    label:'',
                    data: claim ,

                    backgroundColor:[
                     'rgba(255,105,145,0.6)',
                     'rgba(155,100,210,0.6)',
                     'rgb(63, 191, 191)'

                  ]
                 }
              ]
           }
           });
       })
}

【问题讨论】:

  • 看来你已经明白了。您面临的问题是什么?
  • 现在看到我也高亮了代码,我想在“Promise.all”代码中实现,但我不知道怎么做,这就是这里的问题。跨度>
  • 因为我不知道如何处理来自三个不同 API 的请求来渲染饼图
  • 无法理解你的问题..可能应该重新措辞..
  • 有什么看不懂的,能不能好好告诉我一下?

标签: reactjs api promise fetch pie-chart


【解决方案1】:

我做了一些修改,现在它对我来说工作正常,如果有人想要答案,你可以看看我的,它是 100% 工作的:

  constructor(props) {
    super(props);

    this.state = {
      Data: []
    };
  }

  componentDidMount() {
    Promise.all([
      fetch("http://localhost:4000/api/EMEA/E_claimQuarter"),
      fetch("http://localhost:4000/api/EMEA/E_claimQuarter1"),
      fetch("http://localhost:4000/api/EMEA/E_claimQuarter2")
    ])
      .then(([res1, res2, res3]) => Promise.all([res1.json(), res2.json(), res3.json()]))
      .then(([data1, data2, data3]) => 
       { 
        console.log(typeof(data1));

        const array = [...data1, ...data2, ...data3];
        // const A = JSON.strigify(array);
        console.log('hi');
        console.log(array);
        console.log(data1);
        // console.log(A);
        let claim = [];

        array.forEach(element => {
        claim.push(element.COUNT);
        });
        console.log(claim);
        this.setState({
          // Data: data1, data2, data3,
          Data: {
            labels: [
              "FY19 Q1[NOV-JAN]",
              "FY19 Q2[FEB-APR]",
              "FY18 Q3[SEP-NOV]"
            ],
            datasets: [
              {
                label: "",
                data: claim,
                backgroundColor: [
                  "rgba(255,105,145,0.6)",
                  "rgba(155,100,210,0.6)",
                  "rgb(63, 191, 191)"
                ]
              }
            ]
          }
        })
       });
  }

【讨论】:

  • 我觉得您应该寻找一种数据驱动的解决方案,即不硬编码三个季度。假设有一天你想要一个四个季度的图表,拥有一个可以处理任意数量季度的通用函数不是更好吗?写起来不会太难。
  • 感谢@Roamer 的提醒,现在项目只是原型模式,一旦完全进入生产模式,我会进一步优化项目。
  • 我已根据您自己的回答用某些内容覆盖了我的回答。
  • 因为我是整个网络开发的新手
  • 明白 - 你做得很好。
【解决方案2】:

根据 OP 自己的回答,这里有一个更通用的解决方案:

componentDidMount(graphData) {
    return Promise.all(graphData.map(dataObj => dataObj.url))
    .then(results => Promise.all(results.map(res => res.json())))
    .then(results => this.setState({
        'Data': {
            'labels': graphData.map(dataObj => dataObj.label),
            'datasets': [
                {
                    'label': '',
                    'data': results.reduce((prev, next) => prev.concat(next), []),
                    'backgroundColor': graphData.map(dataObj => dataObj.bgColor)
                }
            ]
        }
    }));
}

如您所见,数组方法 .map().reduce() 可以生成一些不错的紧凑代码。

调用如下:

var quartersData = [
    { 'url':'http://localhost:4000/api/EMEA/E_claimQuarter', 'label':'FY19 Q1[NOV-JAN]', 'bgColor':'rgba(255,105,145,0.6)' },
    { 'url':'http://localhost:4000/api/EMEA/E_claimQuarter1', 'label':'FY19 Q2[FEB-APR]', 'bgColor':'rgba(155,100,210,0.6)' },
    { 'url':'http://localhost:4000/api/EMEA/E_claimQuarter2', 'label':'FY18 Q3[SEP-NOV]', 'bgColor':'rgb(63, 191, 191)' }
];

componentDidMount(quartersData)
.then(() => {
    console.log('complete');
});

【讨论】:

    猜你喜欢
    • 2018-09-20
    • 2019-02-08
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2021-03-17
    相关资源
    最近更新 更多