在使用 React-Leaflet 时,我在 Next.js 13 中收到 Window is not Defined 错误。我尝试使用动态导入来解决该问题,并成功解决了 Window is not Defined 错误。
但是,那个地方出现了新的错误。以下错误消息是:
1.错误:水合失败,因为初始 UI 与服务器上呈现的内容不匹配。 警告:期望服务器 HTML 包含
中的匹配项。 在此处查看更多信息:https://nextjs.org/docs/messages/react-Hydration-error
这是地图组件
Map component
"use client"
import { MapContainer, useMap, GeoJSON , Marker, Popup} from 'react-leaflet';
import "leaflet/dist/leaflet.css"
import { TileLayer } from 'react-leaflet';
import { Icon } from 'leaflet';
interface Props {
height: string
width: string
coordinateList?: any
}
export default function CoordinateMap({ height , width }: Props ): JSX.Element {
return (
<MapContainer dragging={false} style={{ height: height, width: width }} scrollWheelZoom={false} zoomControl={false} center={[28.3949, 84.1240]} doubleClickZoom={false} zoom={7} >
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution="© <a href='http://osm.org/copyright'>OpenStreetMap</a> contributors"
/>
</MapContainer>
);
};
如果我直接在主页导入,它会显示 窗口未定义
所以,我决定使用 next/dynamic 中的动态。
MapClient
import dynamic from "next/dynamic";
import CoordinateMap from "./CoordinateMap";
const Map = dynamic(() => import('@/app/_components/GlobalMap/CoordinateMap'), {
ssr: false,
})
export default Map
并将其导入主页
它解决了窗口未定义问题,但它显示以下错误而不是那个
警告:预计服务器 HTML 包含
中的匹配项。 在此处查看更多信息:https://nextjs.org/docs/messages/react-Hydration-error
我认为发生此错误是因为您的MapClient第二行中的导入。
此行:
import CoordinateMap from "./CoordinateMap";
会干扰以下动态导入。
我还刚刚发布了一个关于使用 NextJS 14 设置 React-Leaflet 的完整示例:React-Leaflet 4 与 NextJS 14 |工作设置