React代码报错:undefined is not an object (evaluating 'pray.findIndex')
问题描述
运行以下React代码时出现错误:undefined is not an object (evaluating 'pray.findIndex')
代码如下:
const [pray, setPray] = useState([]); const fetchPray = async county => { const url4 = '-' + county; console.log(url4); fetch(url4) .then(response => response.json()) .then(json => setPray(json)) .then(pray => { let index = pray.findIndex(d => d.MiladiTarihKisa === date); let selectData = pray[index]; setVakitGunes(selectData.Gunes); setVakitImsak(selectData.Imsak); setVakitOgle(selectData.Ogle); setVakitIkindi(selectData.Ikindi); setVakitAksam(selectData.Aksam); setVakitYatsi(selectData.Yatsi); setGunTurkce(selectData.MiladiTarihUzun); }) .catch(error => console.log(error)) .finally(() => setLoading4(false)); };
问题原因及解决办法
核心原因:
setPray(json)是异步更新状态的操作,且后续.then(pray => { ... })中的pray参数并非更新后的状态值——setPray本身无返回值,所以此处pray为undefined,调用findIndex必然报错。修复方案:
- 直接使用接口返回的
json数据处理逻辑,无需依赖异步更新的状态:const [pray, setPray] = useState([]); const fetchPray = async county => { const url4 = '-' + county; console.log(url4); fetch(url4) .then(response => response.json()) .then(json => { setPray(json); // 直接用接口返回的json数据处理 let index = json.findIndex(d => d.MiladiTarihKisa === date); // 增加判断,避免匹配不到数据时出现新错误 if (index !== -1) { let selectData = json[index]; setVakitGunes(selectData.Gunes); setVakitImsak(selectData.Imsak); setVakitOgle(selectData.Ogle); setVakitIkindi(selectData.Ikindi); setVakitAksam(selectData.Aksam); setVakitYatsi(selectData.Yatsi); setGunTurkce(selectData.MiladiTarihUzun); } }) .catch(error => console.log(error)) .finally(() => setLoading4(false)); }; - 额外优化:添加
index !== -1的判断,防止当date无匹配数据时,selectData为undefined引发新的报错。
- 直接使用接口返回的
内容的提问来源于stack exchange,提问作者sweoguzhan
相关产品推荐
相关产品推荐

