React Native开发Uber克隆应用airmap marker latitude空值报错如何解决
报错原因
- 核心错误是
react-native-maps的Marker组件coordinate属性传入的参数结构不符合要求:该属性要求传入直接包含latitude、longitude两个数字字段的对象,你代码中直接传入了origin、destination原始对象,这两个对象的经纬度嵌套在details.geometry.location层级下,没有直接挂载在对象根级,组件读取不到对应字段就会抛出空值报错。 - 额外可能触发场景:页面刚跳转时
origin、destination还未完成赋值,处于null/undefined状态,此时读取嵌套属性也会触发报错。
修复方案
- 替换
Marker的coordinate属性值为你已经预处理好的符合格式要求的对象originLoc、destinationLoc:
// 修正后的Marker部分代码 <Marker coordinate={originLoc} title={'Origin'} /> <Marker coordinate={destinationLoc} title={"Destination"} />
- 增加空值拦截逻辑,避免参数未加载完成时渲染组件触发报错:
const RouteMap = ({ origin, destination }) => { // 新增空值判断,参数未就绪时不渲染地图 if (!origin?.details?.geometry?.location || !destination?.details?.geometry?.location) { return null; // 也可以替换为自定义加载动画组件 } // 原有逻辑保持不变 const originLoc = { latitude: origin.details.geometry.location.lat, longitude: origin.details.geometry.location.lng, }; const destinationLoc = { latitude: destination.details.geometry.location.lat, longitude: destination.details.geometry.location.lng, }; // ...其余代码 }
内容的提问来源于stack exchange,提问作者Mustapha Ahmed Yusuf
相关产品推荐
相关产品推荐

