React Native中fetch获取JSON数据执行map操作报undefined错误如何解决
问题根因
你遇到的undefined is not an object (evaluating 'json.map')报错核心原因是:
第一个.then回调中执行response.json()后没有添加return语句,导致链式调用的下一个.then拿到的json参数是undefined,自然不存在map方法。
修复方案
1 基础修复(仅解决当前报错)
在response.json()前增加return即可,额外加一层数组类型判断可以避免后续接口结构变动引发的同类问题:
CheckifReadLater = async () => { const username = await AsyncStorage.getItem('username'); const isLoggedIn = await AsyncStorage.getItem('isLoggedIn'); if (isLoggedIn == 1 && username) { await fetch(Config.backendAPI+`/readlater.php?username=${username}&select`) .then((response) => { reactotron.log("Response : ",response); return response.json(); // 新增return语句 }) .then((json) => { // 新增数组类型判断 if(Array.isArray(json)){ json.map((product, index) => { if (product.id == this.props.product.id) { this.setState({ isReadLater: true, }) } }); } }) .catch((error) => reactotron.log('This is the error: ',error)) } reactotron.log("Readlater : ",this.state.isReadLater); }
2 优化版(统一语法、提升性能)
既然已经使用了async/await语法,就没必要混用.then链式调用,同时用Array.some()替代map可以在匹配到目标项后提前终止遍历,减少不必要的性能消耗:
CheckifReadLater = async () => { try { const username = await AsyncStorage.getItem('username'); const isLoggedIn = await AsyncStorage.getItem('isLoggedIn'); if (isLoggedIn == 1 && username) { const response = await fetch(Config.backendAPI+`/readlater.php?username=${username}&select`); reactotron.log("Response : ",response); const json = await response.json(); if(Array.isArray(json)){ const hasMatch = json.some(product => product.id == this.props.product.id); if(hasMatch){ this.setState({ isReadLater: true }) } } } reactotron.log("Readlater : ",this.state.isReadLater); } catch (error) { reactotron.log('This is the error: ',error) } }
内容的提问来源于stack exchange,提问作者Ayoub Mafkoud
相关产品推荐
相关产品推荐

