javascript - 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>
)
}
解决方案
您需要在 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>
);
推荐阅读
- html - How to parse addresses from website specifying class in R?
- excel - 如何在excel中每21天增加一次日期
- webpack - 重复使用拆分包
- visual-studio-code - VS Code Insiders - 调试 Notebook Cell
- jquery - 通过下拉列表的'indexof'值获取对象键
- laravel-livewire - 通过 livewire 以自定义数据属性的值作为参数调用函数
- c# - C# XPath / 格式化变量类型 XmlNodeList 的小数位
- numpy - 复杂的间接切片索引:怎么做?
- session - Kong会话插件避免轮询请求更新
- object-detection - 用于对象检测的 ML.NET 预测速度改进