【问题标题】:.filter is not a function. Trying to search through names from API data.filter 不是函数。尝试从 API 数据中搜索名称
【发布时间】:2020-05-09 08:25:55
【问题描述】:

我正在尝试使用国家 API 在此迷你应用中实现搜索过滤器。但是,我收到错误 filter is not a function。

现在我认为这是因为数据必须是数组,filter() 才能工作。我不确定如何访问数据进行搜索。

我正在努力解决这个问题。

我的 console.log 中的示例 response.data

{data: Array(250), status: 200, statusText: "", headers: {…}, config: {…}, …}
            data: Array(250)
                  [0 … 99]
               0:
            name: "Afghanistan"
  topLevelDomain: [".af"]
      alpha2Code: "AF"
      alpha3Code: "AFG"
    callingCodes: ["93"]
         capital: "Kabul"
    altSpellings: (2) ["AF", "Afġānistān"]
          region: "Asia"
       subregion: "Southern Asia"
      population: 27657145
          latlng: (2) [33, 65]
         demonym: "Afghan"
            area: 652230
            gini: 27.8
       timezones: ["UTC+04:30"]

这是显示错误的过滤器函数

const Homepage = () => {
  const [countries, setCountries] = useState('');
  const [searchedCountry, setSearchedCountry] = useState('');

  useEffect(() => {
    console.log('effect');
    axios.get(`https://restcountries.eu/rest/v2/all`).then((response) => {
      console.log(response, 'promise fulfiled');
      setCountries(response.data);
    });
  }, []);

  const handleSearch = (event) => {
    setSearchedCountry(event.target.value);
  };

  // Filter function
  const filteredCountries = countries.filter((country) =>
   country.name.toLowerCase().includes(searchedCountry.toLowerCase())
  );

  return (
    <div className='homepage'>
      <input type='text' onChange={handleSearch} />
      <CountryList countries={countries} />
    </div>
  );
};

如果能更多地了解这一点,那就太好了。 谢谢。

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    countries 的初始值不正确。使用相同的类型作为默认值。

    const [countries, setCountries] = useState([]);
    

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 2016-12-17
      • 2018-12-19
      相关资源
      最近更新 更多