[英]Update tileLayer url in react-leaflet
So I got this code running to render a leaflet ok, trying to replace the url whenever the colorMode changes is the challenge here.所以我运行这段代码来渲染传单,当 colorMode 发生变化时尝试替换 url 是这里的挑战。
useEffect is triggered ok displaying the correct variable but I can't update that TileLayer in any way.触发 useEffect 可以显示正确的变量,但我无法以任何方式更新该 TileLayer。
export const Map = () => { const { colorMode } = useColorMode(); let state = { center: { lat: 51.505, lng: -0.09 }, zoom: 13 }; const colorModeUrl = ['https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 'https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png'] useEffect(() => { console.log(colorMode); }, [colorMode]); return ( <MapContainer center={state.center} zoom={state.zoom} style={{ height: '100%' }}> <TileLayer url={colorMode === 'light' ? colorModeUrl[0] : colorModeUrl[1]} /> </MapContainer> ) }
Looking at the TileLayer documentation , the url
prop is not mutable.查看TileLayer 文档, url
属性是不可变的。 After the initial render the component will not update if the prop is changed:在初始渲染之后,如果 prop 发生更改,组件将不会更新:
However, you can add a ref
to the layer and update the url that way但是,您可以向图层添加ref
并以这种方式更新 url
export const Map = () => {
const ref = useRef(null);
const state = { center: { lat: 51.505, lng: -0.09 }, zoom: 13 };
const { colorMode } = useColorMode();
const light = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
const dark =
"https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png";
};
useEffect(() => {
if (ref.current) {
ref.current.setUrl(colorMode === "light" ? light : dark);
}
}, [colorMode]);
return (
<div>
<MapContainer
center={state.center}
zoom={state.zoom}
style={{ height: "100%" }}
>
<TileLayer ref={ref} url={colorMode === "light" ? light : dark} />
</MapContainer>
</div>
);
};
https://codesandbox.io/s/react-leaflet-forked-1534x?file=/src/index.js:0-1158 https://codesandbox.io/s/react-leaflet-forked-1534x?file=/src/index.js:0-1158
I encountered a similar issue today trying to change the TileLayer using react-leaflet v4.我今天遇到了类似的问题,尝试使用 react-leaflet v4 更改 TileLayer。 As mentioned in the accepted answer, the immutability of the TileLayer url attribute is the problem.正如接受的答案中提到的,TileLayer url 属性的不变性是问题所在。 My dead-simple workaround was to pass a "key" attribute to TileLayer that will change whenever a new tile source is commanded.我非常简单的解决方法是将“关键”属性传递给 TileLayer,只要命令新的瓷砖源,该属性就会改变。 This will force a remount of the TileLayer component.这将强制重新安装 TileLayer 组件。
Hopefully this isn't subtly dangerous or an antipattern, but it seems to work with minimal complexity.希望这不是微妙的危险或反模式,但它似乎以最小的复杂性工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.