簡體   English   中英

如何修復 React 自定義掛鈎中的“只能在 function 組件的主體內調用掛鈎”錯誤?

[英]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 個:

  1. 錯誤地使用鈎子 - 這似乎不是你的情況
  2. 加載了重復的 React
  3. 不匹配的 Dom/React 庫

我猜對你來說應該是 2 或 3 - 檢查你使用的是最新版本的reactreact-dom

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

我不太確定。 但這可能是您沒有導入反應的問題:

import { useState } from 'react'

做,

import React, { useState } from 'react'

我猜是因為鈎子只能在反應函數中使用。 並且不導入反應意味着您在反應之外使用 useState 。


我發現您的代碼問題的另一個罪魁禍首是:

不要在事件處理程序中調用鈎子。

為了解決這個問題,將你的鈎子邏輯移到handleSubmit function之外。 handleSubmit是一個事件處理程序,您不能在事件處理程序中調用鈎子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM