this my protected.tsx,when i one use this on page below,some error comes like
服务器错误
错误:尝试从服务器调用 C:\Importir.id\NextJs\diecast-app pp\hoc\withProtected.tsx 的默认导出,但它位于客户端。不可能从服务器调用客户端函数,它只能呈现为组件或传递给客户端组件的 props。
'use client';
import React from 'react';
import { useUser } from '../context/user';
import { useRouter } from 'next/navigation';
interface ProtectedProps {}
const withProtected = (WrappedComponent: React.ComponentType<ProtectedProps>) => {
const WithProtected: React.FC<ProtectedProps> = (props) => {
const router = useRouter();
const user = useUser();
const { uid } = user;
if (typeof window === 'undefined') {
return null;
}
console.log({ uid });
if (!uid) {
router.replace('/');
return <></>;
}
return <WrappedComponent {...props} />;
};
return WithProtected;
};
export default withProtected;
此页面代码有错误
import React from 'react';
import withProtected from '../hoc/withProtected';
const StorePage: React.FC = () => {
return (
<div>
<h2>Halaman diecast</h2>
</div>
);
};
export default withProtected(StorePage);
请解决我的问题,我真的谢谢你们
该错误是由于尝试在 Next.js 应用程序中的服务器端使用客户端函数造成的。您创建的
withProtected
高阶组件 (HOC) 设计为在客户端工作,但 Next.js 尝试在服务器端渲染 (SSR) 期间在服务器上执行它,这会导致错误.
使用
useEffect
进行客户端操作:由于您正在处理身份验证和路由(本质上是客户端操作),因此您应该在 useEffect 挂钩内执行这些操作。这将确保它们仅在组件安装后在客户端执行。
在服务器端返回占位符:在服务器端渲染期间,返回一个占位符(如 null 或加载组件),直到客户端脚本接管。
在客户端重定向:使用
useRouter
钩子内的 useEffect
执行重定向。
试试这个方法 -
withProtected.tsx
:
'use client';
import React, { useEffect } from 'react';
import { useUser } from '../context/user';
import { useRouter } from 'next/router';
interface ProtectedProps {}
const withProtected = (WrappedComponent: React.ComponentType<ProtectedProps>) => {
const WithProtected: React.FC<ProtectedProps> = (props) => {
const router = useRouter();
const user = useUser();
useEffect(() => {
if (!user.uid) {
router.replace('/');
}
}, [user, router]);
// Return null or a loading component on the server
if (typeof window === 'undefined' || !user.uid) {
return null;
}
return <WrappedComponent {...props} />;
};
return WithProtected;
};
export default withProtected;
页面组件 (
StorePage
) 保持不变:
import React from 'react';
import withProtected from '../hoc/withProtected';
const StorePage: React.FC = () => {
return (
<div>
<h2>Halaman diecast</h2>
</div>
);
};
export default withProtected(StorePage);