我正在构建一个可过滤国家/地区的React App。我遇到的问题是我可以过滤国家/地区,但无法过滤区域。数据来自以下Api https://restcountries.eu/rest/v2/all
。主要组件如下所示:
class Countries extends Component {
constructor() {
super();
this.state = {
countries:[],
regions:[],
searchField:"",
regionField:""
}
};
componentDidMount() {
fetch("https://restcountries.eu/rest/v2/all")
.then(response => response.json())
.then(all => this.setState({ countries: all,
regions: all}))
}
render() {
const { countries, searchField, regionField } = this.state;
const filterCountries = countries.filter(country => country.name.toLowerCase().includes(searchField.toLowerCase()));
const filterRegions = countries.filter(country => country.region.toLowerCase().includes(regionField.toLowerCase()));
return(
<div>
<h1 className="header">Where in the World</h1>
<input
type="search"
placeholder="Search a Country"
onChange={e => this.setState({ searchField: e.target.value })}
/>
<input
type="regions"
placeholder="Filter by Regions"
onChange={e => this.setState({ regionField: e.target.value })}
/>
<CountryList countries={filterCountries} regions={filterRegions}/>
</div>
)
}
}
其他部分用于国家/地区列表:
import React from 'react';
import './CountryList.styles.css'
import { CountryCard } from '../Card/CountryCard';
export const CountryList = (props) => (
<div className='card-list'>
{props.countries.map(country => (
<CountryCard key={country.alpha2Code} country={country} regions={country}/>
))}
</div>
);
有点不确定我在这里缺少什么。谢谢你的帮助。在下面,我添加了CountryCard组件。
export const CountryCard = (props) => (
<div className="card-container">
<img alt="flag" src={props.country.flag}width="100%" height="40%"/>
<h1>{props.country.name}</h1>
<p>Population: {props.country.population}</p>
<p>Region: {props.country.region}</p>
<p>Capital: {props.country.capital}</p>
</div>
)
问题似乎是您实际上没有在组件CountryList中使用region属性。尝试像国家这样传递两个数组:
<CountryList countries={[...filterCountries, ...filterRegions ]} />
您可能希望将“国家”道具名称更改为类似于结果的名称。
解决此问题的一种简单方法是也要遍历props.regions:
import React from 'react';
import './CountryList.styles.css'
import { CountryCard } from '../Card/CountryCard';
export const CountryList = (props) => (
<div className='card-list'>
{props.countries.map(country => (
<CountryCard key={country.alpha2Code} country={country} />
))}
{props.regions.map(region => (
<CountryCard key={region.alpha2Code} country={region} }/>
))}
</div>
);
无论如何,我建议您尝试混合使用两个数组。