【问题标题】:looping through json data in react hooks state在 React hooks 状态下循环遍历 json 数据
【发布时间】:2020-05-14 02:17:55
【问题描述】:

我想在地图中显示我所在州的数据我设法获得了我所在州的纬度和经度问题是每当尝试通过该州进行地图绘制时我总是得到它不是函数错误这是我的部分我在该州拥有的代码和数据:

const [countriesData, setCountriesData] = useState({});
useEffect(() => {
const fetchAPI = async () => {
  setCountriesData(await fetchDataCountries());
};
fetchAPI();
}, [setCountriesData]);

console.log(countriesData);

并像这样映射它:

 {countriesData.map((data)=>(
     <Marker latitude={data.countriesData.latitude}
     longitude={data.countriesData.longitude}/>
     ))}

获取api函数:

export const fetchDataCountries = async () => {
  try {
    const data = await axios.get(url);
    const newData = data.data;
    const modfiedData = newData.map((countryData) => {
      return countryData.coordinates;
    });
    return modfiedData;
  } catch (error) {
    console.log(error);
  }
};

【问题讨论】:

  • 请在实际问题本身中发布所有相关代码/文本。不是图片,也绝对不是图片的链接
  • 请多多包涵,先生,我正在努力让它正常工作,谢谢
  • 对不起先生,我刚刚添加了代码,因为图像没有成功
  • 注意你的 useEffect 使用情况(它每次渲染时都在运行 async 函数)

标签: javascript reactjs mapbox react-map-gl


【解决方案1】:

要使您的map 工作,您需要将您的state 转换为数组,现在它是一个对象。

之后,它可能看起来像这样:

{countriesData.map((country) => (
  <Marker
    latitude={country.latitude}
    longitude={country.longitude}
  />
))}

{countriesData.map(({ latitude, longitude }) => (
  <Marker
    latitude={latitude}
    longitude={longitude}
  />
))}

但要获得更准确的答案,最好有一个 state 内容的示例。

【讨论】:

  • 包含一个 323 数组,在每个数组内部,我有这样的内容:[0 … 99] 和 0:纬度:“53.9333” 经度:“-116.5765”proto:对象我想使用其他的经纬度在地图上显示它
  • 所以我认为上面的代码应该可以帮助您解决问题
  • 不,它仍然说 CountryData.mao in not a function
【解决方案2】:

您正在使用空对象初始化 countriesData,然后您正在获取 API 数据。

假设响应是这样的对象数组:

[
   { latitude: 38.8451, longitude: -37.0294 }
   { ... // other coordinates }
]

将初始状态更改为空数组,如下所示:

const [countriesData, setCountriesData] = useState([]);

另外,更新这个块:

{countriesData.map((data) => <Marker latitude={data.latitude} longitude={data.longitude} />)}

说明map()方法只对数组[]有效,对对象{}无效,因此当组件第一次挂载/初始化时,map方法被执行反对一个对象,从而引发map is not a function 错误。

【讨论】:

  • 我之前尝试过,但仍然卡住了,我的问题是我得到了 4 个 useEffect 调用,我设法使用三元来检查数据是否存在并使用我所说的响应是倍数当我尝试使用console.log(countriesData [0])时,每个对象都在一个对象数组中,我得到0:{latitude:“53.9333”,longitude:“-116.5765”}但我不能进去它使用这些属性
  • 在useEffect中多次出现console.log并不是问题
猜你喜欢
  • 2016-05-14
  • 2021-09-29
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多