React Native中AIRMapMarker组件coordinate属性更新报错求助
我之前也踩过这个坑!看到你遇到Error while updating property 'coordinate' of a view managed by: AIRMapMarker这个报错,大概率是coordinate属性的类型、初始化时机或者数据结构出了问题,我整理了几个亲测有效的排查和解决方向:
确保coordinate的数值是有效的数字类型
AIRMapMarker的coordinate要求必须是包含latitude和longitude的对象,而且这两个值必须是合法的数字,不能是null、undefined或者字符串。你当前的state初始化时latitude和longitude都是null,如果直接把这个状态传给marker,不管是初始化还是更新阶段都会触发报错。解决方式:在渲染marker前先判断数值是否有效,比如:
{this.state.latitude !== null && this.state.longitude !== null && ( <AIRMapMarker coordinate={{ latitude: this.state.latitude, longitude: this.state.longitude }} // 其他marker属性 /> )}检查markers数组的每一项数据结构
如果是通过markers数组批量渲染marker,要确保数组里每个marker对象的coordinate都包含有效的经纬度数字。比如在获取地理位置后更新markers时,直接传入正确的数值:navigator.geolocation.getCurrentPosition( (position) => { const { latitude, longitude } = position.coords; this.setState({ latitude, longitude, markers: [ ...this.state.markers, { coordinate: { latitude, longitude }, // 其他marker属性如title、description等 } ], error: null, }); }, (error) => this.setState({ error: error.message }), { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 } );等待地图初始化完成后再更新marker
有时候地图组件还没完全加载完成就更新marker的coordinate,也会导致原生层的报错。可以借助地图的onMapReady回调来延迟marker的更新操作:<AIRMap style={styles.map} onMapReady={() => { // 在这里执行marker的更新逻辑,比如加载markers数组 this.loadMarkers(); }} > {/* 渲染marker的代码 */} </AIRMap>升级react-native-maps到稳定版本
某些旧版本的react-native-maps(也就是AIRMap所属的库)存在coordinate更新的兼容性bug,尝试升级到最新稳定版本可能直接解决问题:# 使用npm npm install react-native-maps@latest --save # 或者使用yarn yarn add react-native-maps@latest
你可以按照上面的步骤逐一排查,应该能解决这个报错。
内容的提问来源于stack exchange,提问作者johnobc

