React Leaflet更新坐标状态后新增标记无法正常显示问题
问题根因
- 你没有将坐标数据交由React的状态系统管理:普通类属性
this.coords的变更不会触发组件重新渲染,因此render方法不会读取到更新后的值,页面自然不会渲染新的标记点。 - 即使后续改成状态管理,直接对数组执行
push修改原数组的操作也不符合React状态不可变更新的要求,同样可能无法触发更新。
修正方案
直接替换对应代码即可:
class Map extends React.Component { constructor(props) { super(props); // 将坐标数据放到state中管理 this.state = { coords: { path: [ {lat:1, lng:1} ] } } } showPics = async() => { let {value} = await Storage.get({key: 'path' }) let arrayPath = JSON.parse(value) // 生成新的坐标数组,不修改原state数据 const newPath = [...this.state.coords.path] for( let i=0; i < arrayPath.length; i++) { let newPoint = {lat: arrayPath[i].latitude, lng: arrayPath[i].longitude} newPath.push(newPoint) } // 调用setState触发重渲染 this.setState({ coords: { ...this.state.coords, path: newPath } }) } render() { return ( <div className="leaflet-container"> <MapContainer id="map" center={center} zoom={zoom} scrollWheelZoom={false}> <TileLayer attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> {/* 从state中读取坐标,添加key避免React警告 */} { this.state.coords.path.map((eachData, index) => ( <Marker key={index} position= {[eachData.lat, eachData.lng]} /> ))} </MapContainer> <IonFab vertical="bottom" horizontal="end" slot="fixed"> <IonFabButton onClick={() => this.showPics()}> <IonIcon icon={image}></IonIcon> </IonFabButton> </IonFab> </div> ) } }
额外注意
- 示例中用index作为key仅为简化代码,如果你的坐标点有唯一ID,建议替换为对应ID作为key值,性能更优。
- 建议添加逻辑判断存储中拿到的arrayPath是否为有效数组,避免JSON.parse出错导致代码崩溃。
内容的提问来源于stack exchange,提问作者jonsken
相关产品推荐
相关产品推荐

