我正在尝试使用国家/地区 API 在此迷你应用程序中实现搜索过滤器。但是,我收到错误 filter
is not a function。
现在我认为这是因为数据必须是一个数组才能让 filter()
工作。我不确定如何访问搜索数据。
我很难理解这个问题。
来 self 的 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>
);
};
如果能更多地了解这一点就太好了。 谢谢。
最佳答案
您的国家/地区
初始值不正确。使用相同类型作为默认值。
const [countries, setCountries] = useState([]);
关于javascript - .filter 不是一个函数。尝试从 API 数据中搜索名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59872225/