无法读取未定义(React)的属性



我的代码有问题,我有搜索输入和国家列表

当我键入一些单词时,我有一个错误,导致我的应用程序崩溃

我已经试了大约两天来寻找这个问题,但找不到。

这是错误消息:未捕获类型错误:无法读取未定义(读取"filter"(的属性

const Country = ({name, num}) =>{
//console.log(name)  
return (
<div>
<p>{name}</p>
</div>
)} // Component
const Input = ({onSearch, search}) =>{
return (
<div>
Find countries: <input onChange={onSearch} value={search} />
</div>
)} // Component
import { useState, useEffect } from "react";
import axios from "axios";
import Input from "./components/Input";
import Country from "./components/Country";
const App = () => {
const [countryList, setCountryList] = useState();
const [search, setSearch] = useState("");
const [filter, setFilter] = useState(false);
useEffect(() => {
axios
.get("https://restcountries.com/v3.1/all")
.then((res) => setCountryList(res.data));
}, []);
const onSearch = (event) => {
if (event.target.value === " ") setFilter(false);
else {
setFilter(true);
setSearch(event.target.value);
}
};
const countriesList = filter 
? countryList.filter((country) => {
return country.name.common.includes(search);
})
: null ;
return (
<div>
<Input onSearch={onSearch} search={search} />
{filter ? (
countriesList.length === 0 ? (
<h3>No match</h3>
) : countriesList.length > 10 ? (
<h3>Too many matches, specify another filter...</h3>
) : countriesList.length < 10 && countriesList.length > 1 ? (
countriesList.map((country, i) => (
<Country name={country.name.common} key={i} num={false} />
))
) : (
<Country name={countriesList[0].name.common} num={true} /> &&
console.log("common", countriesList)
)
) : (
<h3>Search for any country</h3>
)}
</div>
);
};

countrylist状态必须是一个数组。

尝试使用countyList中的数组作为其未定义的初始

const [countryList, setCountryList] = useState([]);

此外,您似乎正在访问过滤器(在组件初始化时直接访问状态值(。请尝试用以下代码替换。如果问题仍然存在,请告诉我,应该是一个非常简单的修复

const [countriesList, setCountriesList] = useState([]);
useEffect(()=>{
if(filter){
setCountriesList(
countryList.filter((country) => {
return country?.name?.common?.includes(search);
}))
}else{
setCountriesList(countryList);
}
},[filter])

相关内容

  • 没有找到相关文章

最新更新