![](/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.