任何人都可以在React中使用.map()时解决类型错误问题吗?

问题描述 投票:0回答:2

任何人都可以帮助我解决此错误吗?我正在尝试从以下API路径提取国家名称的下拉选择器:https://api.covid19api.com/countries

TypeError: Country.map is not a function
at fetchCountries (index.js:29)
at async fetchAPI (CountryPicker.jsx:13)

这里是我正在工作的两个代码部分:

CountryPicker.jsx

import React, { useState, useEffect } from 'react';
import { NativeSelect, FormControl } from '@material-ui/core';

import styles from './CountryPicker.module.css';

import { fetchCountries } from '../../api';

const CountryPicker = () => {
  const [fetchedCountries, setFetchedCountries] = useState([]);

  useEffect(() => {
    const fetchAPI = async () => {
      setFetchedCountries(await fetchCountries());
    };

    fetchAPI();
  }, [setFetchedCountries]);
  console.log(fetchedCountries);


  return (
    <FormControl className={styles.formControl}>
      <NativeSelect >
        <option value="">Global</option>
      </NativeSelect>
    </FormControl>
  );
};

export default CountryPicker;

index.js

import axios from 'axios';

const summary = 'https://api.covid19api.com/summary';
const countriesURL = 'https://api.covid19api.com/countries';

export const fetchData = async () => {
    try {
        const { data: { Global: { NewConfirmed, TotalConfirmed, NewDeaths, TotalDeaths, NewRecovered, TotalRecovered, }, Date } } = await axios.get(summary);



        return {  NewConfirmed, TotalConfirmed, NewDeaths, TotalDeaths, NewRecovered, TotalRecovered, Date };

    } catch (error) {
        console.log(error);

    }
}

//TODO
//Fetch Daily Data for charts using axios

export const fetchCountries = async () => {
    try {
      const { data: [ {Country} ] } = await axios.get(countriesURL);



     return Country.map((Country) => Country);
    } catch (error) {
      console.log(error);

    }
  };

[我试图查看为什么可能会发生错误,并且我发现.map()不适用于非数组变量,但是我不确定当前的实现,如何解决此问题

API中的数据如下:

[
    {"Country":"Micronesia, Federated States of","Slug":"micronesia","ISO2":"FM"},
    {"Country":"Bangladesh","Slug":"bangladesh","ISO2":"BD"},
    {"Country":"Bouvet Island","Slug":"bouvet-island","ISO2":"BV"},
    // ...and so on...
]
javascript reactjs
2个回答
1
投票

查看调用API的结果,它是这种形式:

[
    {"Country":"Micronesia, Federated States of","Slug":"micronesia","ISO2":"FM"},
    {"Country":"Bangladesh","Slug":"bangladesh","ISO2":"BD"},
    {"Country":"Bouvet Island","Slug":"bouvet-island","ISO2":"BV"},
    // ...and so on...
]

所以Country不是数组,它是数组中每个对象的属性。

如果您的目标是从每个对象中提取Country属性,请使用数组,然后使用map提取该属性,也许要进行结构分解:

const data = await axios.get(countriesURL);
return data.map(({Country}) => Country);

0
投票

您无法解构数组内部的键。 { data: [ {Country} ] }错误,您将得到不确定的

export const fetchCountries = async () => {
    try {
      const contries = await axios.get(countriesURL).then(x => data);



     return contries.map(({Country}) => Country);
    } catch (error) {
      console.log(error);
    }
  };
© www.soinside.com 2019 - 2024. All rights reserved.