我正在尝试将
react-leaflet
地图添加到混音应用程序中。我使用 npx create-remix@latest
命令创建了一个简单的应用程序。然后我使用安装说明添加了
react-leaflet
。现在我有以下代码:
index.tsx
import type { MetaFunction } from "@remix-run/node";
import { ClientOnly } from "remix-utils/client-only";
import LazyMap from "~/components/LazyMap";
export const meta: MetaFunction = () => {
return [
{ title: "New Remix App" },
{ name: "description", content: "Welcome to Remix!" },
];
};
export default function Index() {
return (
<div>
test 123
<ClientOnly fallback={<p>Loading...</p>}>
{() => <LazyMap />}
</ClientOnly>
</div>
);
}
LazyMap.tsx
import { Suspense, lazy } from 'react';
const Map = lazy(() => import('./Map'));
export default function LazyMap() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Map />
</Suspense>
);
}
地图.tsx
import { MapContainer } from 'react-leaflet/MapContainer'
// import { Marker } from 'react-leaflet/Marker'
// import { Popup } from 'react-leaflet/Popup'
// import { TileLayer } from 'react-leaflet/TileLayer'
import { ClientOnly } from 'remix-utils/client-only';
export default function Map() {
return (
<div>
test 123
<ClientOnly>
{() => (
<MapContainer zoom={13} scrollWheelZoom={false}>
test
</MapContainer>
)}
</ClientOnly>
</div>
);
}
尽管我已经将
Map
包装在来自 LazyMap
的惰性导入中,但它似乎仍在尝试处理 Map
文件,这当然会引用传单并导致可怕的 ReferenceError: window is not defined
错误。我怎样才能克服这个错误?
当
rendering组件导致对某些仅限客户端的全局变量(如
ClientOnly
或window
)的引用时,document
实用程序非常有用,但它只能包装您导入的组件代码,并且导入可以有副作用...比如引用 window
或 document
。
根据官方混音文档,您可以在文件中添加
.client.ts/tsx/js/jsx
后缀,以将其从 SSR 中排除。