gpt4 book ai didi

javascript - TypeError : Cannot read property 'Countries' of undefined. 为什么对象数组不被识别,不被过滤?

转载 作者:行者123 更新时间:2023-12-04 03:24:34 25 4
gpt4 key购买 nike

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

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

TypeError: Cannot read property 'Countries' of undefined.

为什么对象数组不被识别,不被过滤?在另一个文件中,map方法遍历相同的写入data.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>
)
}

最佳答案

当您从 api 获取数据时,在将任何高阶函数应用于数组时需要使用可选链接 ? 以防数据尚未加载。例如

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

关于javascript - TypeError : Cannot read property 'Countries' of undefined. 为什么对象数组不被识别,不被过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67843597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com