如何解决Next.js React Leaflet Map 未正确显示
我有下一张传单地图:
但是没有正确显示任何东西,只有当我拖动地图并且只加载您可以在左上角看到的部分作为第二张图片时。
我发现错误仅在第一次渲染时发生,如果我在没有刷新的情况下导航到其他页面(下一个链接组件),则它会正确显示。
我的代码:
import React,{ useState } from "react";
import { MapContainer,Marker,Popup,TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";
function Map({ coordinates }) {
const [position,setPosition] = useState(coordinates);
return (
<MapContainer center={position} zoom={100} scrollWheelZoom={false} style={{ height: "500px",width: "100%" }}>
<TileLayer attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<Marker position={position}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
);
}
export default Map;
我已经安装了 react-reaflet
和 leaflet
,我还导入了 CSS 并指定了容器的宽度和高度,正如 Stack Overflow 中的其他解决方案所示,但没有任何效果。
我如何在 Next 中导入组件(因为传单不支持服务器端渲染):
/**
* Leaflet makes direct calls to the DOM when it is loaded,therefore React Leaflet is not compatible with server-side rendering.
* @see https://stackoverflow.com/a/64634759/9244579
*/
const Map = dynamic(() => import("../../components/Map"),{
loading: () => <p>Map is loading</p>,ssr: false,// This line is important. It's what prevents server-side render
});
解决方法
我刚刚解决了这个问题。
我发现如果我调整窗口大小,地图显示正确,所以我必须做的是每 100 毫秒调用一次 invalidateSize() 函数,以使屏幕大小一直更新,这将在第一次起作用也渲染。
import React,{ useState,useEffect } from "react";
import { MapContainer,Circle,TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";
function Map({ coordinates }) {
const position = coordinates;
const fillBlueOptions = { fillColor: "#0484D6" };
const [map,setMap] = useState(null);
useEffect(() => {
if (map) {
setInterval(function () {
map.invalidateSize();
},100);
}
},[map]);
return (
<MapContainer center={position} zoom={20} scrollWheelZoom={false} style={{ height: "400px",width: "100%" }} whenCreated={setMap}>
<TileLayer attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<Circle center={position} pathOptions={fillBlueOptions} radius={50} />
</MapContainer>
);
}
export default Map;
考虑到您必须向 MapContainer 组件添加属性 whenCreated={setMap}
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。