javascript - 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 function
Select 标签。不知道我错过了什么。任何帮助,将不胜感激。
解决方案
您正在尝试迭代 Set,Sets 不公开 .map 方法。您应该在迭代之前将集合转换回数组。请试试这个,看看它是否有效。
<select onChange={this.handleRegion} value={regionField}>
{Array.from(new Set(countries.map(country=>country.region)))
.map(uniqueRegion =>
<option>{uniqueRegion}</option>)}
</select>
推荐阅读
- c++ - C ++:使用关键字运算符重载成员的构造函数
- python - 如何在 Python 中使用 Django 让 html/css 框架更快?
- hadoop - 为什么 HDFS ACL max_entries 设置为 32?
- python - 累积税收计算器
- javascript - 如何根据组件类型过滤Vue中的子组件?
- apache-spark - 如何获取pyspark数据框的相关矩阵?
- javascript - hls.js 防止倒带和保留段
- ios - CognitoIdentityCredentials 无权执行:lambda:InvokeFunction on resource
- php - 获取 4 张不同尺寸的图片
- r - 带有翻转坐标和多面图的ggplot排序轴