【问题标题】:Cannot change state in Axios ReactJS and cannot retrieve data in orderAxios ReactJS 中无法更改状态,无法按顺序检索数据
【发布时间】:2020-04-15 15:29:28
【问题描述】:

我正在尝试从 RapidAPI 的 API 中获取 COVID-19 的统计数据。我想按日期获取统计信息,将数据插入图表。问题是 API 链接中只能包含日期,如下所示:

https://covid-19-data.p.rapidapi.com/report/totals?date-format=undefined&format=undefined&date=2020-04-15

我所做的是使用 for 循环获取十个日期并使用 Axios 检索每天的数据,如下所示:

const today = new Date();
const dd = String(today.getDate()).padStart(2, '0');
const mm = String(today.getMonth() + 1).padStart(2, '0');

const [labels, setLabels] = useState([])

useEffect(() => {

    for(let i=dd-10; i<dd; i++) {
        Axios({
            method: 'GET',
            url: `https://covid-19-data.p.rapidapi.com/report/totals?date-format=undefined&format=undefined&date=2020-${mm}-${i}`,
            headers: {
                "x-rapidapi-host": "covid-19-data.p.rapidapi.com",
                "x-rapidapi-key": "cfb0f14a9fmsh913ae802309e7c9p175585jsn825aebcbd5ac"
            }
        })
        .then(response => {
            let temp = [...labels]
            temp.push(response.data[0].date)
            setLabels(temp)
        })
        .catch(error => {
            console.log(error)
        })
    }

}, [])

问题在于,每次 Axios 检索新日期时,labels 都会更改,而不是将新日期附加到 labels 数组。

我在网上做了一些研究,人们说数据尚未加载,因此当我设置状态时,它有点设置空的东西之类的东西,但我不太明白他们在说什么。

除此之外,当它检索数据时,它不会按顺序检索它。例如,今天是 4 月 15 日,它应该按如下顺序检索数据:05 06 07 08 09 10 11 12 13 14,但它只是随机跳转。如果我在 .then() 处进行控制台记录,则会出现:

如您所见,它不按顺序排列。

请帮我看看,我已经用谷歌搜索了解决方案,但无济于事。

【问题讨论】:

  • 为什么它没有按顺序返回?
  • 调用是异步的,所以我们没有任何保证哪个会先完成。使用Promise.all,该函数仅在所有函数完成后才解析。现在我们确定结果在那里,我们可以按正确的顺序返回它们。
  • 好的,我试试,谢谢

标签: javascript reactjs api axios


【解决方案1】:

那是因为结果是异步接收的,状态是同步更新的。 试试这个解决方案

useEffect(() => {
  const today = new Date();
  const dd = String(today.getDate()).padStart(2, "0");
  const mm = String(today.getMonth() + 1).padStart(2, "0");

  const fetchData = async (date) => {
    if (date >= dd) return;

    const result = await Axios({
      method: "GET",
      url: `https://covid-19-data.p.rapidapi.com/report/totals?date-format=undefined&format=undefined&date=2020-${mm}-${date}`,
      headers: {
        "x-rapidapi-host": "covid-19-data.p.rapidapi.com",
        "x-rapidapi-key": "cfb0f14a9fmsh913ae802309e7c9p175585jsn825aebcbd5ac",
      },
    });

    setLabels((val) => {
      let temp = [...val];
      temp.push(result.data[0].date);
      return temp;
    });
    fetchData(++date);
  };

  fetchData(dd - 10);
}, []);

【讨论】:

  • 这解决了它,但我不太明白。如何在不使用任何循环函数的情况下循环日期?
  • 我使用了递归,fetchData 正在调用自己,直到日期到达当前日期。
猜你喜欢
  • 2020-09-20
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 2020-01-25
  • 2016-09-06
  • 2020-02-28
  • 2021-10-06
相关资源
最近更新 更多