首页 > 解决方案 > 如何修复 React 自定义钩子中的“只能在函数组件的主体内调用钩子”错误?

问题描述

[解决了]

我正在尝试创建一个自定义挂钩以在项目中使用。它应该提交一个有效载荷并返回一个结果,但我收到了这个错误:

Uncaught Invariant Violation:钩子只能在函数组件的主体内部调用。

当页面加载时,错误发生在控制台中。我什至不需要点击按钮。

这是我的自定义钩子(useSubmit):

import { useState } from 'react'

export const useSubmit = submitFunction => {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  const handleSubmit = async args => {
    try {
      setLoading(true)
      setError(null)
      return submitFunction(...args)
    } catch (error) {
      setError(error)
    } finally {
      setLoading(false)
    }
  }
  return [handleSubmit, loading, error]
}

这是我的功能组件中的相关代码:

import React from 'react'
import { useSubmit } from '../../../../../../../utils/custom-hooks/use-submit'
import { createGameRules } from '../../../../../../services/game/rules'

export const GameRules = () => {
  const [handleSubmit, loading, error] = useSubmit(createGameRules)

  // Some code here

  const saveGameRules = async () => {
    const payload = {
      title: 'Some title',
      rules: 'Some description'
    }

    const savedGameRule = await handleSubmit(payload)
    console.log(savedGameRule)
  }

  // More code here

   return (
      <button onClick={() => saveGameRules()}>Save</button>
   )

这是我的服务,将数据发布到端点并返回结果:

import axios from '../../axios'

export const createGameRules = async payload => {
  const { title, rules } = payload
  const { data: { data } } = await axios({
    method: 'POST',
    url: '/game/rules',
    data: {
      title,
      rules
    }
  })

  return data
}

我错过了什么?谢谢您的帮助!!


[编辑]

问题是项目中有另一个 package.json 文件。因为自定义钩子位于另一个 package.json 的层次结构中,所以应用程序试图使用另一个版本的 React。

解决方案是将自定义钩子移到更内部的级别,在适当的 package.json 旁边,所以一切正常。

线索在一些人引用的链接https://reactjs.org/warnings/invalid-hook-call-warning.html上,但我不知道这个其他 package.json

谢谢大家的帮助。

标签: javascriptreactjsreact-hooks

解决方案


出现此错误的原因有 3 个:

  1. 错误地使用钩子 - 这似乎不是你的情况
  2. 加载了重复的 React
  3. 不匹配的 Dom/React 库

我猜对你来说应该是 2 或 3 - 检查你使用的是最新版本的reactand react-dom

https://reactjs.org/warnings/invalid-hook-call-warning.html


推荐阅读