使用axios时无法设置状态。每次都会返回承诺

我正在构建Covid-19跟踪器并从JSON获取数据。我试图通过将鼠标悬停在地图上来显示全省范围的数据。

这是获取数据的代码

import axios from "axios";

export const fetchDailyData = async () => {
  try {
    const getData = await axios.get("http://localhost:8080/h3");
   console.log(getData.data);
 return (getData.data);
  } catch (error) {console.log(error);}
};

这是处理地图的代码

import React, { useState, useEffect } from "react";
import { ComposableMap, Geographies, Geography } from "react-simple-maps";
import { scaleQuantile } from "d3-scale";
import ReactTooltip from "react-tooltip";
import { fetchDailyData} from "../api/dataprocess";
import LinearGradient from "./LinearGradient.js";
import "./CanadaMap.scss";

/**
 * Courtesy: https://rawgit.com/Anujarya300/bubble_maps/master/data/geography-data/india.topo.json
 * Looking topojson for other countries/world?
 * Visit: https://github.com/markmarkoh/datamaps
 */
const CANADA_TOPO_JSON = require("../../../src/canada.topo.json");

const PROJECTION_CONFIG = {
  scale: 100,
  center: [-106.3468, 68.1304] // always in [East Latitude, North Longitude]
};

// Red Variants
const COLOR_RANGE = [
  "#ffedea",
  "#ffcec5",
  "#ffad9f",
  "#ff8a75",
  "#ff5533",
  "#e2492d",
  "#be3d26",
  "#9a311f",
  "#782618"
];

const DEFAULT_COLOR = "#EEE";

// const getRandomInt = () => {
//   return parseInt(Math.random() * 100);
// };

const geographyStyle = {
  default: {
    outline: "none"
  },
  hover: {
    fill: "#ccc",
    transition: "all 250ms",
    outline: "none"
  },
  pressed: {
    outline: "none"
  }
};

// will generate random heatmap data on every call
const getHeatMapData = () => {
  return [
    { id: "MB", state: "Manitoba", value: 2},
    { id: "NB", state: "New Brunswick", value: 2 },
    { id: "AB", state: "Alberta", value: 27 },
    { id: "NF", state: "Newfoundland and Labrador", value: fetchDailyData() },
    { id: "NS", state: "Nova Scotia", value: 1 },
    { id: "SK", state: "Saskatchewan", value: 21 },
    { id: "PE", state: "Prince Edward Island", value: 22 },
    { id: "QC", state: "Quebec", value: 40000 },
    { id: "ON", state: "Ontario", value: 67 },
    { id: "BC", state: "British Columbia", value: 26 },
    { id: "YU", state: "Yukon", value: 27 },
    { id: "NT", state: "Northwest Territories", value: 2 },
    { id: "NU", state: "Nunavut", value: 50 }
  ];
};

function CanadaMap() {
  const [tooltipContent, setTooltipContent] = useState("");
  //const [latest, setLatest] = useState(processedData());

  /**
   * If info in search is empty then i show all the countries
   */
  // const filterCountry =result.filter(item=>{
  //   return searchCountry !== "" ? item.country.includes(searchCountry):item;
  // });

  const [data, setData] = useState(getHeatMapData());

  const gradientData = {
    fromColor: COLOR_RANGE[0],
    toColor: COLOR_RANGE[COLOR_RANGE.length - 1],
    min: 0,
    max: data.reduce((max, item) => (item.value > max ? item.value : max), 0)
  };

  const colorScale = scaleQuantile()
    .domain(data.map(d => d.value))
    .range(COLOR_RANGE);

  const onMouseEnter = (geo, current = { value: "NA" }) => {
    return () => {
      setTooltipContent(`${geo.properties.name}: ${current.value}`);
    };
  };

  const onMouseLeave = () => {
    setTooltipContent("");
  };

  const onChangeButtonClick = () => {
    setData(getHeatMapData());

  };

  return (
    <div className="full-width-height container">
      <h1 className="no-margin center">States and UTs</h1>
      <ReactTooltip>{tooltipContent}</ReactTooltip>
      <ComposableMap
        projectionConfig={PROJECTION_CONFIG}
        projection="geoMercator"
        width={600}
        height={220}
        data-tip=""
      >
        <Geographies geography={CANADA_TOPO_JSON}>
          {({ geographies }) =>
            geographies.map(geo => {
              //console.log(geo.id);
              const current = data.find(s => s.id === geo.id);
              return (
                <Geography
                  key={geo.rsmKey}
                  geography={geo}
                  fill={current ? colorScale(current.value) : DEFAULT_COLOR}
                  style={geographyStyle}
                  onMouseEnter={onMouseEnter(geo, current)}
                  onMouseLeave={onMouseLeave}
                />
              );
            })
          }
        </Geographies>
      </ComposableMap>
      <LinearGradient data={gradientData} />
      <div className="center">
        <button className="mt16" onClick={onChangeButtonClick}>
          Change
        </button>
      </div>
    </div>
  );

}

export default CanadaMap;

我正在尝试通过此行获取数据

{ id: "NF", state: "Newfoundland and Labrador", value: fetchDailyData() },

这是App.js

function App() {


  /
  return (
    <div className='Container' >
     <h1 className="title fadeInUp" style={{animationDelay: '0.3s'}}>Canada</h1>

    <CanadaMap />
    </div>


  );
}

export default App;

This is the mapand the error i am getting on hover

Hovering over the map results in multiple calls to the API like this

console.log语句

const getData = await axios.get("http://localhost:8080/h3");
   console.log(getData.data);

gives this result

我试图将鼠标悬停在地图上并显示从JSON获取的数据。有没有一种方法可以正确地管理状态并将其存储在中央位置,以便我可以访问它(在React中管理状态对我来说是很新的事情。)是否有可能从promise中提取数据而不进行多次调用API。

评论
  • nipsa
    nipsa 回复

    fetchDailyData is async function so it will always return promise :

    解决方案:

    const getHeatMapData = async () => { // <---- HERE
      return [
        { id: "MB", state: "Manitoba", value: 2},
        { id: "NB", state: "New Brunswick", value: 2 },
        { id: "AB", state: "Alberta", value: 27 },
        { id: "NF", state: "Newfoundland and Labrador", value: await fetchDailyData() }, // <--- HERE
        { id: "NS", state: "Nova Scotia", value: 1 },
        { id: "SK", state: "Saskatchewan", value: 21 },
        { id: "PE", state: "Prince Edward Island", value: 22 },
        { id: "QC", state: "Quebec", value: 40000 },
        { id: "ON", state: "Ontario", value: 67 },
        { id: "BC", state: "British Columbia", value: 26 },
        { id: "YU", state: "Yukon", value: 27 },
        { id: "NT", state: "Northwest Territories", value: 2 },
        { id: "NU", state: "Nunavut", value: 50 }
      ];
    };