NextJS |当我将受保护的身份验证导入页面时出现打字稿问题

问题描述 投票:0回答:1
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);

请解决我的问题,我真的谢谢你们

typescript next.js server-side protected high-order-component
1个回答
0
投票

该错误是由于尝试在 Next.js 应用程序中的服务器端使用客户端函数造成的。您创建的

withProtected
高阶组件 (HOC) 设计为在客户端工作,但 Next.js 尝试在服务器端渲染 (SSR) 期间在服务器上执行它,这会导致错误.

  1. 使用

    useEffect
    进行客户端操作:由于您正在处理身份验证和路由(本质上是客户端操作),因此您应该在 useEffect 挂钩内执行这些操作。这将确保它们仅在组件安装后在客户端执行。

  2. 在服务器端返回占位符:在服务器端渲染期间,返回一个占位符(如 null 或加载组件),直到客户端脚本接管。

  3. 在客户端重定向:使用

    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);
© www.soinside.com 2019 - 2024. All rights reserved.