简体   繁体   English

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

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

[SOLVED] [解决了]

I am trying to create a custom hook to use in the project.我正在尝试创建一个自定义挂钩以在项目中使用。 It should submit a payload and return a result, but I am getting this error:它应该提交一个有效载荷并返回一个结果,但我收到了这个错误:

Uncaught Invariant Violation: Hooks can only be called inside the body of a function component.未捕获的不变违规:只能在 function 组件的主体内部调用挂钩。

The error happens in the console when the page loads.当页面加载时,错误发生在控制台中。 I don't even need to click on the button.我什至不需要点击按钮。

This is my custom hook (useSubmit):这是我的自定义钩子(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]
}

This is the relevant code from my functional component:这是我的功能组件中的相关代码:

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>
   )

Here is my service, to post the data to the endpoint and return the result:这是我的服务,将数据发布到端点并返回结果:

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
}

What am I missing?我错过了什么? Thanks for the help!!谢谢您的帮助!!


[EDIT] [编辑]

The problem was that there was another package.json file in the project.问题是项目中有另一个 package.json 文件。 Because the custom hook was in the hierarchy of this other package.json, the application was trying to use another version of React.因为自定义钩子在另一个 package.json 的层次结构中,所以应用程序试图使用另一个版本的 React。

The solution was to move the custom hook to a more internal level, next to the appropriate package.json, so everything worked.解决方案是将自定义挂钩移动到更内部的级别,在适当的 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 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

Thank you all for your help.谢谢大家的帮助。

There are 3 reasons that this error occurs:出现此错误的原因有 3 个:

  1. using hooks wrongly - this doesn't seem to be your case错误地使用钩子 - 这似乎不是你的情况
  2. Duplicate React loaded加载了重复的 React
  3. Mismatched Dom/React libraries不匹配的 Dom/React 库

I would guess it would be 2 or 3 for you - check you are using the latest versions of react and react-dom .我猜对你来说应该是 2 或 3 - 检查你使用的是最新版本的reactreact-dom

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

I'm not pretty sure.我不太确定。 But it might be the issue that you have not imported react:但这可能是您没有导入反应的问题:

import { useState } from 'react'

Do,做,

import React, { useState } from 'react'

I guess it because hooks can only be used inside react functions.我猜是因为钩子只能在反应函数中使用。 And without importing react means you're using useState outside the react.并且不导入反应意味着您在反应之外使用 useState 。


Another culprit I found the issue with your code is:我发现您的代码问题的另一个罪魁祸首是:

Do not call hooks in event handlers.不要在事件处理程序中调用钩子。

To solve this, move your hooks logic outside the handleSubmit function.为了解决这个问题,将你的钩子逻辑移到handleSubmit function之外。 handleSubmit is an event handler and you cannot call hooks inside event handler handleSubmit是一个事件处理程序,您不能在事件处理程序中调用钩子

暂无
暂无

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

相关问题 反应钩子错误:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React hook Error: Invalid hook call. Hooks can only be called inside of the body of a function component 错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。 通过路由反应 - Error: Invalid hook call. Hooks can only be called inside of the body of a function component. by Routing in react 错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。 - 反应 - Error: Invalid hook call. Hooks can only be called inside of the body of a function component. - React 反应本机:.! 错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用 - React Native !!! Error: Invalid hook call. Hooks can only be called inside of the body of a function component React 17:错误:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React 17: Error: Invalid hook call. Hooks can only be called inside of the body of a function component React Native:错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用 - React Native: Error: Invalid hook call. Hooks can only be called inside of the body of a function component 反应,得到错误:无效的钩子调用。 Hooks 只能在函数组件的主体内部调用 - React, getting Error: Invalid hook call. Hooks can only be called inside of the body of a function component React - 错误:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React - Error: Invalid hook call. Hooks can only be called inside of the body of a function component 反应原生。 错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用 - React Native. Error: Invalid hook call. Hooks can only be called inside of the body of a function component 自定义挂钩错误:只能在 function 组件的主体内部调用挂钩 - Custom hook error: Hooks can only be called inside of the body of a function component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM