Функция карты продолжает повторять вывод - PullRequest
0 голосов
/ 27 апреля 2020

Я делаю небольшое приложение React, которое получает данные от API стран. Я хочу использовать тэг Select в React. Это так, что я могу отфильтровать регионы стран на странице. Так что, если кто-то выбирает Европу, он возвращает европейские страны или Африку, затем африканские страны и так далее. Я просмотрел этот пост на предмет использования тега select . Однако проблема в том, что список повторяется. enter image description here

Ниже приведен код, который у меня есть:

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 })}
                        />

                        {/* < SearchBox type="regions" placeholder="Filter by Regions" handlechange={e=> this.setState({
                            regionField: e.target.value })}
                            /> */}
                        <select onChange={this.handleRegion}>
                            {countries.map(region => (
                                <option key={region.alpha2Code}>
                                    {region.region}
                                </option>
                            ))}
                        </select>

                </div>
                <CountryList countries={filterCountries} />

            </div>

       )
     }
   }

  export default Countries

Не уверен что я пропустил Любая помощь будет оценена.

Ответы [ 2 ]

2 голосов
/ 27 апреля 2020

Понятно, что ваша проблема не в самом коде, а в способе обработки данных. Вы отображаете массив стран, поэтому для каждой страны есть поле региона. В теге select вы получаете все страны, но вместо того, чтобы показывать их имена, они показывают регион, к которому они принадлежат.

0 голосов
/ 27 апреля 2020

Вы передаете Страны этому <CountryList countries={filterCountries} />. Я надеюсь, что вы не зацикливаетесь на визуализации стран в этом компоненте.

Это:

<select onChange={this.handleRegion}>
    {countries.map(region => (
        <option key={region.alpha2Code}>
            {region.region}
        </option>
    ))}
</select>

правильно, но вам нужно добавить атрибут значения <select onChange {this.handleRegion} value={regionField}>

Также раскомментируйте привязку с помощью ключевого слова this в конструкторе для метода handleRegion.

Отредактировано

let regions = [];
    fetch("https://restcountries.eu/rest/v2/all")
        .then(response => response.json())
        .then(all => {
            // Get unique regions here using Set
            let uniqueRegions = new Set();
            all.forEach(item => {
                uniqueRegions.add(item.region);
            });

            for (item of uniqueRegions) {
                regions.push(item);
            };

            this.setState({
                countries: all,
                regions: regions
            })
        });
...