React (Next.JS) 页面加载后导入组件
React (Next.JS) Import Component After Page Loaded
我正在使用 react-owl-carousel
包,但是当我刷新页面时它会抛出一条错误消息“window 未定义”,所以没错。模块在加载页面之前尝试访问 window 对象。我尝试使用 React.lazy 但它不起作用,我的页面抛出另一个错误 reactdomserver does not yet support suspense
(我试图更改 next.config.js 以使用它但仍然抛出该错误。)
问题是我需要这样的东西
import OwlCarousel from "react-owl-carousel" //import it just like that right after page loaded (or window object is accesible)
Next.js supports ES2020 dynamic import() for JavaScript. With it you
can import JavaScript modules dynamically and work with them. They
also work with SSR.
您可以导入您的组件 dynamicaly
并禁用服务器端渲染,这样它将可以访问 window
创建您的组件并在那里使用 OwlCarousel
import React from 'react';
import OwlCarousel from 'react-owl-carousel';
const OwlComponent = () => {
return (
<div>
<OwlCarousel />
</div>
);
};
现在将该组件作为动态组件导入
import dynamic from "next/dynamic";
const OwnComponentNoServerRendering = dynamic(() =>
import("../components/OwlComponent"), { ssr: false });
它应该起到魅力的作用
我正在使用 react-owl-carousel
包,但是当我刷新页面时它会抛出一条错误消息“window 未定义”,所以没错。模块在加载页面之前尝试访问 window 对象。我尝试使用 React.lazy 但它不起作用,我的页面抛出另一个错误 reactdomserver does not yet support suspense
(我试图更改 next.config.js 以使用它但仍然抛出该错误。)
问题是我需要这样的东西
import OwlCarousel from "react-owl-carousel" //import it just like that right after page loaded (or window object is accesible)
Next.js supports ES2020 dynamic import() for JavaScript. With it you can import JavaScript modules dynamically and work with them. They also work with SSR.
您可以导入您的组件 dynamicaly
并禁用服务器端渲染,这样它将可以访问 window
创建您的组件并在那里使用 OwlCarousel
import React from 'react';
import OwlCarousel from 'react-owl-carousel';
const OwlComponent = () => {
return (
<div>
<OwlCarousel />
</div>
);
};
现在将该组件作为动态组件导入
import dynamic from "next/dynamic";
const OwnComponentNoServerRendering = dynamic(() =>
import("../components/OwlComponent"), { ssr: false });
它应该起到魅力的作用