首页 > 解决方案 > TypeError: (intermediate value).map is not a function when using set for Country Api

问题描述

我正在构建一个从 API 请求数据的 React 应用程序。现在作为应用程序的一部分,我想按 Api 的区域进行过滤。现在我意识到我需要使用 Sets 来提取区域。以下是我到目前为止的代码:

import React, { Component } from 'react';
import { CountryList } from './Components/Card-List/CountryList';
import { SearchBox } from './Components/Search-box/Search-Box';
import { NavBarCard }from './Components/NavBar/NavBarCard';
import './Countries.styles.css';


class Countries extends Component {
constructor() {
    super();
    this.state = {
        countries:[],
        searchField:"",
        regionField:"",
        darkMode: false
    }
    this.setDarkMode = this.setDarkMode.bind(this);
    this.handleRegion = this.handleRegion.bind(this);
};


componentDidMount() {
    fetch("https://restcountries.eu/rest/v2/all")
    .then(response => response.json())
    .then(all =>  this.setState({ countries: all,
        regions: all}))
}


setDarkMode(e){
    this.setState((prevState) => ({ darkMode: !prevState.darkMode }));
}

handleRegion(e){
    this.setState({regionField: e.target.value})
}
render() {
    const { countries, searchField, regionField, darkMode } = this.state;
    const filterCountries = countries.filter((country) => country.name.toLowerCase().includes(searchField.toLowerCase()) &&
     country.region.toLowerCase().includes(regionField.toLowerCase()));

     return(


            <div className={darkMode ? "dark-mode" : "light-mode" }>

                 <NavBarCard handlechange={this.setDarkMode} moonMode={darkMode ? "moon fas fa-moon" : "moon far fa-moon"} darkMode={darkMode ? "dark-mode" : "light-mode"}/>


                <div className="Input">

                    < SearchBox type="search" placeholder="Search a Country" handlechange={e=> this.setState({
                        searchField: e.target.value })}
                        />


                        <select onChange={this.handleRegion} value={regionField}>
                            {new Set(countries.map(country=>country.region))
                            .map(uniqueRegion => 
                            <option>{uniqueRegion}</option>)}
                        </select>
                </div>
                <CountryList countries={filterCountries} />

            </div>

         )
       }
     }

   export default Countries;

我得到的错误是TypeError: (intermediate value).map is not a functionSelect 标签。不知道我错过了什么。任何帮助,将不胜感激。

标签: javascriptreactjsapiselectset

解决方案


您正在尝试迭代 Set,Sets 不公开 .map 方法。您应该在迭代之前将集合转换回数组。请试试这个,看看它是否有效。

<select onChange={this.handleRegion} value={regionField}>
{Array.from(new Set(countries.map(country=>country.region)))
.map(uniqueRegion => 
<option>{uniqueRegion}</option>)}
</select>


推荐阅读