小编Dev*_*son的帖子

类型错误:无法使用 useEffect 和 Axios 读取未定义的属性“get”

我正在尝试在 React 钩子中获取一些数据。这里没什么特别的,只是一些加载文本,然后在我的数据加载后替换。

但是我一直点击我的 catch 块并Failed to fetch data: Cannot read property 'get' of undefined TypeError: Cannot read property 'get' of undefined打印到控制台。

import React, { useState, useEffect } from "react";
import { axios } from "axios";

const DataPanel = () => {
  let [isLoading, setLoading] = useState(false);
  let [data, setData] = useState();

  useEffect(() => {
    async function getData() {
      let response;
      setLoading(true);
      try {
        response = await axios.get("urltosomewhere");
        setData(response);
      } catch (e) {
        console.log(`Failed to fetch data: ${e.message}`, …
Run Code Online (Sandbox Code Playgroud)

async-await reactjs axios use-effect use-state

3
推荐指数
1
解决办法
1334
查看次数

在 Promise.all 中使用 .map

因此,我有一些需要在 Express 服务器的 init 上运行的承诺。

const dates = [];
for (var i = 0; i <= 8; i++) {
  dates.push(
    moment()
      .add(i, "days")
      .format("YYYY-MM-DD")
  );
}
const [cityName, weatherData, celestialData] = await Promise.all([
  axios.get(
    `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${myKey}`
  ),
  axios.get(
    `https://api.darksky.net/forecast/${myKey}/${latitude},${longitude}`
  ),
  dates.map(date => {
    axios.get(
      `https://api.ipgeolocation.io/astronomy?apiKey=${myKey}&lat=${latitude}&long=${longitude}&date=${date}`
    );
  })
]);
Run Code Online (Sandbox Code Playgroud)

我需要 8 个不同天的数据,所以我想通过运行带有日期数组的 .map,我会得到另一个数组,其中包含每个数组的已解决承诺。这并不像我预期的那样工作。如何管理 Promise.all 内循环的 axios 调用?

javascript promise axios

2
推荐指数
1
解决办法
879
查看次数