【问题标题】:React useState Hooks with JSON data outputting array of arrays instead of one array使用 JSON 数据输出数组数组而不是一个数组来反应 useState Hooks
【发布时间】:2021-11-30 16:23:50
【问题描述】:

我在 react 应用程序中有一个 useEffect 挂钩,用于调用异步函数,向我们的快速服务器发送 axios 请求以提取 JSON 数据。我遇到了一个问题,即从请求中提取的数据未正确设置为状态变量。在下面的代码中,我们 console.log 从请求中提取的数据,它正在输出一个数据数组,这正是我们想要的。但是,在使用拉取的内容设置状态变量并记录状态变量的输出之后,它的输出似乎比数组更多。就好像状态变量变成了一个数组数组,而不是仅仅将它设置为与提取数据相同的数组。我们应该设置状态变量的特定方法吗?在之前的 useEffect 函数中,我们以类似的方式对外部源进行了另一个 api 调用,它似乎正确地设置了状态变量。我们的应用程序终端的屏幕截图也会显示我们的状态变量的输出。

import { MapContainer, TileLayer, Marker, Popup, Circle } from "react-leaflet";
import React, { useState, useEffect } from "react";
import mockData from "./testData/MOCK_DATA.json";
import axios from "axios";
import outageData from "./testData/outageData.json";

function OutageIndicator({ outage }) {
  //this component renders the markers with corresponding lat and long values calculated by the geocodify api.
  const [coords, setCoords] = useState();

  useEffect(() => {
    async function resolveLocation() {
      const resp = await axios.get(
        "https://api.geocodify.com/v2/geocode/json?api_key=mykey&q=" +
          outage.outage_street +
          ", " +
          outage.outage_city +
          ", Michigan, USA"
      );
      const [lng, lat] = resp.data.response.bbox;
      setCoords({ lng, lat });
    }
    resolveLocation();
  }, [outage]);

  return !coords ? (
    "Loading"
  ) : (
    <Marker position={[coords.lat, coords.lng]}>
      <Popup>
        {outage.service_type} {outage.service_name}
      </Popup>
    </Marker>
  );
}

function OutageMap() {
  //This is where the map page will be rendered.
  const [allOutages, setAllOutages] = useState();
  useEffect(() => {
    async function fetchOutages() {
      const resp = await axios.get("/outages");
      const pulledOutages = resp.data.outages;
      //console.log(pulledOutages); //This outputs a single array that is pulled from the api call
      setAllOutages({ pulledOutages });
      console.log(allOutages); //this outputs an array of arrays that are similar to pulledOutages
    }
    fetchOutages();
  });

  return (
    <MapContainer center={[38.89, -77.059]} zoom={13} scrollWheelZoom={true}>
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      //outageData below is dummy data that was hard coded. This would change to allOutages once the state variable is set correctly.
      {outageData.outages.map((mock) => (
        <OutageIndicator outage={mock} />
      ))}
    </MapContainer>
  );
}

export default OutageMap;

【问题讨论】:

    标签: javascript reactjs json express react-hooks


    【解决方案1】:

    您是否尝试过使用setAllOutages(pulledOutages) 而不是setAllOutages({ pulledOutages }) 设置状态?

    在对象中放置一个数组会做一些奇怪的事情,例如:

    const a = [1,2,3];
    const b = {a};
    console.log(JSON.stringify(b));

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 2021-01-05
      • 2021-08-10
      • 2019-11-29
      • 1970-01-01
      • 2017-12-21
      • 2020-06-03
      • 1970-01-01
      • 2020-06-03
      相关资源
      最近更新 更多