繁体   English   中英

如何修复 React 自定义挂钩中的“只能在 function 组件的主体内调用挂钩”错误?

[英]How to fix 'Hooks can only be called inside the body of a function component' error in React custom hook?

[解决了]

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

未捕获的不变违规:只能在 function 组件的主体内部调用挂钩。

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

这是我的自定义钩子(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 旁边,所以一切正常。

The clue was at the link https://reactjs.org/warnings/invalid-hook-call-warning.html cited by some, but I didn't know about this other package.json

谢谢大家的帮助。

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

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

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

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

我不太确定。 但这可能是您没有导入反应的问题:

import { useState } from 'react'

做,

import React, { useState } from 'react'

我猜是因为钩子只能在反应函数中使用。 并且不导入反应意味着您在反应之外使用 useState 。


我发现您的代码问题的另一个罪魁祸首是:

不要在事件处理程序中调用钩子。

为了解决这个问题,将你的钩子逻辑移到handleSubmit function之外。 handleSubmit是一个事件处理程序,您不能在事件处理程序中调用钩子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM