[已解决]
我正在尝试创建一个自定义挂钩,以便在项目中使用。它应该提交一个有效载荷并返回一个结果,但我得到了这个错误:
未捕获的不变冲突:钩子只能在函数组件内部调用
加载页面时,控制台中会出现错误。我甚至不需要点击按钮。
这是我的自定义挂钩(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
}
我错过了什么?谢谢你的帮助!!
[EDIT]
问题是项目中有另一个package.json文件。由于自定义钩子位于另一个package.json的层次结构中,因此该应用程序正试图使用另一个版本的React。
解决方案是将自定义钩子移到一个更内部的级别,在适当的package.json旁边,这样一切都正常了。
线索就在链接处https://reactjs.org/warnings/invalid-hook-call-warning.html被一些人引用,但我不知道其他包.json
谢谢大家的帮助。
出现此错误有三个原因:
- 错误地使用钩子-这似乎不是你的情况
- 加载重复React
- Dom/Rect库不匹配
我想对你来说应该是2或3——检查你是否使用了最新版本的react
和react-dom
。
https://reactjs.org/warnings/invalid-hook-call-warning.html
我不太确定。但这可能是你没有导入反应的问题:
import { useState } from 'react'
Do,
import React, { useState } from 'react'
我想是因为钩子只能在react函数内部使用。不导入react意味着您在react之外使用useState。
我发现你的代码有问题的另一个罪魁祸首是:
不要在事件处理程序中调用钩子。
要解决此问题,请将钩子逻辑移动到handleSubmit函数之外。handleSubmit
是一个事件处理程序,不能在事件处理程序中调用钩子