筛选提交函数异常:Uncaught TypeError: country.name.match is not a function
问题修复方案
核心报错原因
你调用country.name.match()时报错,是因为restcountries v3 API返回的country.name是一个对象,不是字符串,对象没有match方法。该API的name对象包含common(通用名称)、official(官方名称)等字符串属性,你需要指定具体属性来调用match方法。
代码问题梳理与修复
你的代码还有两个额外问题:
- React状态更新是异步的,调用
setNewFilter(event.target.value)后,立刻使用newFilter拿不到最新值 filteredCountries被定义成了函数,直接传给setCountries会导致状态变成函数类型,而非数组
修复后的代码:
const handleFilterSubmit = (event) => { const inputValue = event.target.value setNewFilter(inputValue) const regex = new RegExp(inputValue, 'i') const filteredCountries = countries.filter(country => country.name.common.match(regex)) setCountries(filteredCountries) }
补充说明
如果需要匹配官方名称,把country.name.common换成country.name.official即可;另外建议给countries初始值设为空数组,避免组件初始化时执行filter报错。
内容的提问来源于stack exchange,提问作者jnatividad
相关产品推荐
相关产品推荐

