我正在尝试使用 React 的 useEffect 挂钩更改 tileLayer。这在从 DarkMode 切换到 LightMode Theme 时停止,从而将 tileLayer 更改为 Dark,反之亦然。
我已经阅读了数百页并尝试了许多替代方案,但它根本不起作用。有人能帮助我吗?
反应叶 v3.2.0
import React, { useState, useEffect, useContext } from "react";
import { Grid } from "@material-ui/core";
import { DarkContext } from '../../../Context/DarkContext';
import { MapContainer, Marker, Popup, TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import icon from "../constants";
const zoom = 13;
function Map({ regionCoord, regionName }) {
const [map, setMap] = useState(null);
const { isDarkModeCont } = useContext(DarkContext);
const L = require("leaflet");
const mapa1 = L.tileLayer("https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png")
const mapa2 = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png")
function turnLightMap() {
mapa1.removeFrom(map);
mapa2.addTo(map);
}
function turnDarkMap() {
mapa2.removeFrom(map);
mapa1.addTo(map);
}
// useEffect(() => {
// if(isDarkModeCont == true) {
// turnDarkMap()
// } else {
// turnLightMap()
// }
// }, [isDarkModeCont])
return (
<>
<Grid container>
<Grid item xs={10}>
{regionCoord && (
<MapContainer
center={[50, 50]}
zoom={zoom}
style={{ height: "90vh" }}
whenCreated={setMap}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url={"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"}
/>
<Marker position={regionCoord} icon={icon}>
<Popup>{regionName}</Popup>
</Marker>
</MapContainer>
)}
</Grid>
<Grid item xs={2}>
<button onClick={() => turnLightMap()}>Light Map</button>
<button onClick={() => turnDarkMap()}>Dark Map</button>
</Grid>
</Grid>
</>
);
}
export default Map;
单击按钮会更改地图,但如果我激活 useEffect 它会显示此错误: