React Native中Axios调用Google Places API后数据无法在UI显示的问题
问题分析与解决
核心问题1:API返回数据结构处理错误
Google Places Details API的返回结果里,餐厅名称、地址等核心数据都嵌套在response.data.result字段下,你现在直接把整个response.data存入state,导致result.name找不到对应值——因为name根本不在这个层级。
核心问题2:空状态返回不符合React规则
当result为null时,你返回的是console.log('nodata'),但React组件必须返回合法的JSX元素(或null),这种返回会引发渲染异常,就算后续数据加载完成,也可能无法正常更新UI。
额外优化:useEffect依赖缺失
你的useEffect依赖数组为空,但id来自导航参数,若后续id发生变化,组件不会重新触发API请求,需把id加入依赖数组。
修改后的代码
import React, { useState, useEffect } from 'react'; import { View, Text, StyleSheet } from 'react-native'; import axios from "axios"; const GResultsShowScreen = ({ navigation }) => { const [result, setResult] = useState(null); const baseURL = 'https://maps.googleapis.com/maps/api/place/details/json?key=MYAPIKEY'; const id = navigation.getParam('id'); const getResult = async (placeId) => { try { const response = await axios.get(baseURL, { params: { place_id: placeId } }); // 存储API返回的result字段,这才是餐厅的具体数据 setResult(response.data.result); } catch (err) { console.error('请求失败:', err); } }; useEffect(() => { if (id) { // 确保id存在再发起请求 getResult(id); } }, [id]); // 将id加入依赖数组 // 空状态返回合法JSX if (!result) { return <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>加载中...</Text> </View>; } return ( <View style={{ flex: 1, padding: 16 }}> <Text>test {result.name} </Text> </View> ); }; const styles = StyleSheet.create({}); export default GResultsShowScreen;
验证要点
- 控制台打印
result时,会直接看到包含name字段的餐厅对象 - UI中的
result.name会正常渲染出餐厅名称 - 当导航参数
id变化时,组件会自动重新请求对应餐厅的数据
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

