![](/img/trans.png)
[英]React hook Error: Invalid hook call. Hooks can only be called inside of the body of a function component
[英]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 个:
我猜对你来说应该是 2 或 3 - 检查你使用的是最新版本的react
和react-dom
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.