React项目react-leaflet的Map组件props变更后不重新渲染如何解决
问题根因
你使用的react-leaflet v3及以上版本中,MapContainer(你代码里别名是LeafletMap)的center和zoom属于仅初始化属性,只有组件第一次挂载时生效,后续props更新不会触发地图视图变更,这是框架本身的设计逻辑。
解决方案
第一步:修改自定义Map组件,监听props变更主动更新地图视图
需要通过useRef获取地图实例,用useEffect监听center和zoom的变化,调用原生leaflet的setView方法更新视图,修改后的Map组件代码如下:
import React, { useEffect, useRef } from 'react'; import './Map.css'; import { MapContainer as LeafletMap, TileLayer } from 'react-leaflet'; function Map({center, zoom}) { const mapRef = useRef(null); // 监听center和zoom变化,主动更新地图视图 useEffect(() => { if (mapRef.current) { mapRef.current.setView(center, zoom); } }, [center, zoom]); return ( <div className="map"> <LeafletMap ref={mapRef} center={center} zoom={zoom}> <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution='© <a href="http://osm.org.copyright">OpenStreetMap</a> contributors' /> </LeafletMap> </div> ) } export default Map
第二步:修复App组件中全球选项的坐标异常问题
你当前代码选择WorldWide时调用的是/all接口,返回数据中没有countryInfo字段,会导致坐标赋值为undefined,需要在onCountryChange方法里做兼容处理:
const onCountryChange = async (event) => { const countryCode = event.target.value; const url = countryCode === "WorldWide" ? "https://disease.sh/v3/covid-19/all" : `https://disease.sh/v3/covid-19/countries/${countryCode}` await fetch(url).then(response => response.json()).then(data => { setCountry(countryCode); setCountryInfo(data); // 兼容全球选项的坐标和缩放 if (countryCode === "WorldWide") { setMapCenter([-34, -64]); setMapZoom(3); } else { setMapCenter([data.countryInfo.lat, data.countryInfo.long]); setMapZoom(4); } }); };
完成以上两步修改后,切换国家时地图就会自动调整到对应国家的中心位置和缩放等级了。
内容的提问来源于stack exchange,提问作者Anagh Basak
相关产品推荐
相关产品推荐

