有一天,我更新了我的应用程序到React18,发现在反应传单的行为发生了一些变化。在我的项目中,我为传单地理编码器编写了一个自定义包装器,然后在MapContainer中使用它。
地编码器:
export const Geocoder: FC<{}> = props => {
//#region --Constants--
const map: L.Map = useMap();
const {t, i18n} = useTranslation();
//#endregion
//#region --States--
//#endregion
//#region --Hooks--
useEffect(() => {
Initialize();
}, []);
//#endregion
//#region --Functions--
const Initialize = (): void => {
const controller: MapController = new MapController();
const geocoderControl: GeocoderControl = geocoder({
geocoder: geocoders.mapbox({
apiKey: controller.Token,
geocodingQueryParams: {
language: i18n.language
}
}),
defaultMarkGeocode: false,
placeholder: t("search"),
errorMessage: t("noResult")
});
geocoderControl.on("markgeocode", result => {
const codingResult: GeocodingResult = result.geocode ?? result;
map.fitBounds(codingResult.bbox);
const newPopup: L.Popup = popup()
.setLatLng(codingResult.bbox.getCenter())
.setContent(codingResult.html ?? codingResult.name)
.openOn(map);
});
geocoderControl.addTo(map);
};
//#endregiony
//#region --Render--
return null;
//#endregion
};在MapContainer中使用React传单:
<MapContainer center={props.latLng ?? defaultPosition} zoom={13} scrollWheelZoom={true}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url={mapController.BaseUrl}
accessToken={mapController.Token}
id={eLayer.STREETS}
/>
{
props.enableGeoCoding ?
<Geocoder/>
: null
}
<Markers latLng={props.latLng} fieldSetter={props.fieldSetter}/>
</MapContainer>使用了17种React版本,所有这些都起了作用,并产生了以下结果:

这是正确的,地图只显示一个地编码器。但是现在在React18中,它看起来是这样的:

在此之后,我用react devtools创建了一个配置文件,并查看了为什么这再次呈现,结果是useMap()钩子在GeoCoder包装中似乎发生了变化。
您知道为什么这个钩子在18版本之后会发生变化吗?在代码方面,React17和18在我的代码中没有什么改变。
发布于 2022-07-29 21:21:32
这可以通过保存对Geo编码器的引用,并在清除钩子时从地图中删除控件来解决。
https://stackoverflow.com/questions/73101684
复制相似问题