【问题标题】:Invalid hook call in API route无效的钩子调用 - nextjs API 路由
【发布时间】:2021-08-09 03:44:41
【问题描述】:

我正在尝试使用 next-auth 保护 API 端点,但端点返回错误“无效的挂钩调用”

以下是 API 端点的完整代码:

import Sale from '../../../../models/Sale';
import dbConnect from '../../../../utils/dbConnect';
import { useSession, getSession } from 'next-auth/client'



export default async function handler({query: {number}}, res) {

  const [session, loading] = useSession()
  await dbConnect();

  if (typeof window !== 'undefined' && loading) return null

  if (!session) {
    res.status(403)
    return <p> Unauthorized </p>
  }

  if (session) {
    const date = new Date();
    const currentYear = date.getFullYear();
    const firstYear = currentYear - number + 1;

    const sales = await Sale.find({
      orderYear: {
        $gte: firstYear
      },
      subTotal: {
        $gt: 3000
      }
    }).exec()

    if (!sales || !sales.length) {
      res.status(400).json({
        error: 'No records found for date range'
      })
    } else {
      res.status(200).json({
        data: {
          sales: sales,
          count: sales.length
        }
      })
    }
  }

}

export async function getServerSideProps(context) {
  const session = await getSession(context)
  return {
    props: {
      session
    }
  }
}

这是完整的错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

我已经阅读了文档,但我不明白我在这里对钩子的使用是不正确的。

我应该如何使用 useSession() 钩子?

【问题讨论】:

    标签: reactjs next-auth


    【解决方案1】:

    正如错误提示的那样,你只能在React功能组件内部调用钩子。

    这个函数不是React 组件,它是一个API 路由,就像你说的那样。我对 NextJS 不是很了解,但是您需要的功能可能存在于其他地方。您从一个名为 next-auth/client 的库中导入它的事实有点引起怀疑。

    【讨论】:

    • 是的,你是对的。我使用的是页面/客户端代码示例而不是 API 路由。
    猜你喜欢
    • 2022-01-08
    • 2021-08-11
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2022-12-05
    • 2020-12-02
    相关资源
    最近更新 更多