使用Google Maps API与RapidAPI时报错Cannot read properties of null (reading 'sw')
报错根因
你的bounds状态初始值为null,监听coordinates和bounds的useEffect会在组件首次渲染时立即触发,此时Google Maps组件还未完成加载、也未调用setBounds给bounds赋值,直接访问bounds.sw就会触发读取null属性的类型错误。
解决方案
1. 给接口调用增加非空判断
修改App.js中的useEffect逻辑,仅在bounds的sw和ne属性都存在时才调用接口:
useEffect(() => { // 非空校验,避免bounds为空时执行逻辑 if (bounds?.sw && bounds?.ne) { getPlacesData(bounds.sw, bounds.ne).then((data) => { console.log(data); setPlaces(data); }); } }, [coordinates, bounds]);
如果你的运行环境不支持可选链操作符,可替换为if (bounds && bounds.sw && bounds.ne)。
2. 确认Google Maps边界回调配置正确
检查你使用的Google Maps组件是否正确绑定了边界变化事件,确保每次地图视口变化时都会更新bounds状态,参考示例:
// 假设你使用@react-google-maps/api库 const mapRef = useRef(null); <GoogleMap ref={mapRef} center={coordinates} zoom={14} onBoundsChanged={() => { const newBounds = mapRef.current.getBounds(); const ne = newBounds.getNorthEast(); const sw = newBounds.getSouthWest(); setBounds({ ne: { lat: ne.lat(), lng: ne.lng() }, sw: { lat: sw.lat(), lng: sw.lng() } }); }} />
3. 接口函数增加参数校验(可选兜底方案)
在API层的getPlacesData函数中新增参数合法性校验,避免上游传入空值时抛出错误:
import axios from "axios"; const URL = "https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary"; export const getPlacesData = async (sw, ne) => { // 参数合法性校验,不合法直接返回空数组 if (!sw?.lat || !sw?.lng || !ne?.lat || !ne?.lng) return []; try { const { data: { data }, } = await axios.get(URL, { params: { bl_latitude: sw.lat, bl_longitude: sw.lng, tr_longitude: ne.lng, tr_latitude: ne.lat, }, headers: { "x-rapidapi-host": "travel-advisor.p.rapidapi.com", "x-rapidapi-key": "key", }, }); return data; } catch (error) { console.log(error); return []; } };
内容的提问来源于stack exchange,提问作者Priyam
相关产品推荐
相关产品推荐

