javascript - 如何修复 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
谢谢大家的帮助。
解决方案
出现此错误的原因有 3 个:
- 错误地使用钩子 - 这似乎不是你的情况
- 加载了重复的 React
- 不匹配的 Dom/React 库
我猜对你来说应该是 2 或 3 - 检查你使用的是最新版本的react
and react-dom
。
推荐阅读
- java - 无法初始化类 com.android.sdklib.repositoryv2.AndroidSdkHandler
- firebase - 有没有办法在没有云功能的情况下触发 Firestore?
- python - 对于 Matplotlib 图表,Tkinter 滚动条不滚动
- python - 迭代不同值的函数
- javascript - Eslint 对齐所有对象值
- javascript - firebase.collection.doc.get 正在运行多次
- python - 为什么我的 pygame 屏幕在等待用户输入时没有响应?
- javascript - 如何链接.where进行firebase查询
- python-3.x - Python 列表复制垃圾回收
- python - 使用 Python 将 HTML 文件写入 Confluence 时出现问题