开发者问题收集

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

2022-10-28
1724

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

当我输入一些单词时,出现错误,导致我的应用程序崩溃

我花了大约两天时间寻找问题,但找不到它。

这是错误消息:未捕获的类型错误:无法读取未定义的属性(读取“过滤器”)

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>
  );
};
2个回答

countrylist state 必须是一个数组。

Gibson
2022-10-28

尝试在 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])
Vikas Saini
2022-10-28