首页 > 解决方案 > TypeError:无法读取未定义的属性“国家/地区”。为什么无法识别和过滤对象数组?

问题描述

我从 API ('https://api.covid19api.com/summary') 获取一个对象。这个对象有一个带有对象数组的键国家和我需要过滤的这个对象数组。

    const filteredData = data.Countries.filter(dat => {
        return dat.Country.toLowerCase().includes(searchfield.toLowerCase());
      })

TypeError:无法读取未定义的属性“国家/地区”。

为什么无法识别和过滤对象数组?在另一个文件中,map 方法迭代相同的写入数据。Countries 没有错误。

const Home = () => {
    const [data, setData] = useState();
    const [searchfield, setSearchfield] = useState('')
    useEffect(() => {
        const fetch = async () => {
            try{
                const res = await axios.get('https://api.covid19api.com/summary');
                setData(res.data);
            }catch(error){
                console.log(error);
            }
        };
        fetch();
    }, []);
    
    const onSearchChange = (event) => {
        setSearchfield(event.target.value)
      }

      const filteredData = data.Countries.filter(dat => {
        return dat.Country.toLowerCase().includes(searchfield.toLowerCase());
      })   
    
     return (
        <div className="main-container">
            <Header searchChange={onSearchChange}/>
            <div className="wrapper">
                <Card data={data}/>
                {/*<div className="graph">
                    <h1>Global Pandemic Crisis Graph</h1>
                    <img src={COVID.image} alt=""/>
                </div>*/}
                <div className="countries">
                    <Countries data={filteredData}/>
                </div>
            </div>
            {/*<Footer />*/}
        </div>
    )
}

标签: javascriptreactjs

解决方案


您需要在 axios 响应的回调中过滤您的数据,否则它将是“未定义的”,因为它还没有完成获取它。

  let filteredData = useRef(null);
  useEffect(() => {
    if (typeof data !== "undefined")
      filteredData.current = data.Countries.filter((dat) => {
        return dat.Country.toLowerCase().includes(searchfield.toLowerCase());
      });
  }, [data]);

  const fetch = async () => {
    const res = await axios
      .get("https://api.covid19api.com/summary")
      .then((response) => {
        // response.data should not be "undefined" here.
        setData(response.data);
      })
      .catch((error) => {
        // Error fallback stuff
        console.error(error);
      });
  };
  if (!filteredData.current) fetch();

稍后在您的代码中,您可以检查它是否已被定义,

  return (
    <div className="main-container">
      <div className="wrapper">
        {filteredData.current !== null &&
          filteredData.current.map((CountryMap, i) => 
          <div key={i}>{CountryMap.Country}</div>
          )
        }
      </div>
    </div>
  );

推荐阅读