graphql - 如何在Nextjs中间件中使用Hook?

标签 graphql next.js

我有一个这样的中间件

import type { NextFetchEvent, NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { useCheckIsAdminQuery } from "../../generated/graphql";

export function middleware(req: NextRequest, ev: NextFetchEvent) {
    
    const {data,loading,error} = useCheckIsAdminQuery()
    if(data?.checkIsAdmin){
        return NextResponse.next()
    }else{
        const url = req.nextUrl.clone()
        url.pathname = '/404'
        return NextResponse.redirect(url)
    }

    
}

useCheckIsQuery() 只是 codegen 包生成的一个钩子(Hook),但我无法在中间件中调用这个钩子(Hook)。 错误显示

Invalid hook call. Hooks can only be called inside of the body of a function component. 

如何修复它?

最佳答案

根据 React 文档:“不要在循环、条件或嵌套函数内调用 Hooks。相反,在任何早期返回之前,始终在 React 函数的顶层使用 Hooks。” .

Nextjs 的中间件不是 React 函数,因此您不能在其中使用钩子(Hook)。解决您的问题的方法是使用您的自定义逻辑创建一个钩子(Hook),并在您想要生效的页面中手动调用它。

关于graphql - 如何在Nextjs中间件中使用Hook?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71781696/

相关文章:

GraphQL - 如何将返回值用作下一个查询的变量?

javascript - 我的 graphql 服务器突变返回空值

node.js - 为什么我的 Express 服务器响应仅在 SSR 期间被截断?

Apollo Server 2 中没有 CDN 的 GraphQL Playground

vue.js - 通过slug获取页面和页面数据。 Strapi 和 Nuxt

graphql - 无法自定义 graphql 枚举的值

reactjs - 在 next.js 中带有 css 模块的 tailwind css

reactjs - 无法读取 nextJs 中 razorpay 付款的 null 属性 'tagName'

javascript - 下一页Js :pid routes

reactjs - 区分大小写的 URL 与 NextJS 10 问题