React Native调用Google Maps API Fetch JSON时出现undefined报错求助
解决Fetch获取Google Maps数据时
info.result.name undefined的问题 问题根源分析
- 初始状态类型不匹配:你把
info初始值设为数组[],但Google Maps返回的是对象结构,数组没有result属性,初始阶段访问info.result直接报错。 - Loading状态逻辑颠倒:渲染时
!isLoading显示LOADING,但实际流程是初始isLoading为true,useEffect里立刻设为false并发起请求,请求完成后又设回true——这会导致请求还没结束就尝试渲染数据,此时info还是空数组,自然触发错误。 - Fetch URL格式错误:密钥参数写法错误,应该是
key=你的私有密钥,而非$"'privatekey'",这会导致请求返回异常数据,进一步引发result不存在的问题。 - 缺少空值保护:即使请求成功,也可能存在返回数据无
result的情况,直接访问info.result.name会触发报错。
修复后的代码
const [isLoading, setLoading] = useState(true); // 初始值改为空对象,匹配API返回的数据类型 const [info, setInfo] = useState({}); const getInfo = () => { // 修正URL的密钥参数格式 fetch(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?place_id=${resturant.id}&key=你的私有密钥`) .then((response) => { // 先校验请求是否成功 if (!response.ok) { throw new Error('请求失败'); } return response.json(); }) .then((json) => setInfo(json)) .catch((error) => console.error(error)) // 请求完成后结束加载状态 .finally(() => setLoading(false)); } useEffect(() => { getInfo(); }, []); return( <View style={style.card}> {/* 加载状态逻辑修正:isLoading为true时显示加载提示 */} {isLoading ? <Text>LOADING</Text> : <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 10 }}> {/* 用可选链避免undefined报错,同时设置默认值 */} <Text>{info.result?.name || '暂无名称'}</Text> </View> } </View> )
额外建议
- 确认Google Maps API密钥已正确配置,且已启用Nearby Search API权限,否则请求会返回错误。
- 在
.then(json)中先打印返回的数据,确认结构是否符合预期,避免因API返回格式变更导致问题。
内容的提问来源于stack exchange,提问作者Tommaso Ceredi
相关产品推荐
相关产品推荐

