NextJS有单页应用模式吗



我有一个使用React&NextJS。目前,我有一个自定义的_app.js,使页面成为SSR。但现在我希望页面不在服务器端加载。有办法做到这一点吗?

我们可以使用next.js动态导入(https://nextjs.org/docs/advanced-features/dynamic-import):

import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(() => import('../components/hello3'), { ssr: false })

你也可以写类似HOC:

import React from 'react';
const isClient = () => typeof window !== 'undefined';
export const withClientRenderOnly = <P extends Record<string, unknown>>(
WrappedComponent: React.ComponentType<P>
) => {
const WrappedWithClientRenderOnly: React.FC<P> = props => {
if (!isClient()) return null;
return <WrappedComponent {...props} />;
};
return WrappedWithClientRenderOnly;
};

或者创建简单的合成:

const ClientRenderOnly: React.FC = ({ children }) => {
const [isMounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if(!isMounted) return null;
return children;
};
const Page = () => <ClientRenderOnly>Page</ClientRenderOnly>

所以你想用SSR构建SPA,对吧?我很困惑,因为你说你现在不想要服务器端渲染。如果你不想要SSR,为什么要使用NextJs?,原因NextJs用于SSR

还有一点是,自定义的"_app.js"并不能使它成为SSR。以下是您可以使用自定义APP 进行的功能

  • 在页面更改之间保持布局
  • 导航页面时保持状态
  • 使用componentDidCatch自定义错误处理
  • 将附加数据注入页面
  • 添加全局CSS

(https://nextjs.org/docs/advanced-features/custom-app)

nextjs中有三种类型的渲染服务器端渲染、服务器端生成和客户端渲染。创建一个自定义应用程序不会使其成为SSR。请看一下文件

最新更新