首页 > 解决方案 > 在自定义钩子中使用钩子时触发的钩子错误使用无效?

问题描述

我需要有关自定义挂钩的帮助。我创建了一个自定义挂钩来进行 api 调用(useApiCall),我从我的authActions.js文件中调用它,以将用户名和密码发送到服务器以注册新用户。我收到一条错误消息,提示我想念在useApiCall功能组件中使用钩子。

当我删除useApiCalluseReducer功能组件中的逻辑时,它说我误用了. 它不会让我在 React 功能组件中使用钩子。useStateuseReduceruseApiCall

我知道我违反了钩子规则,但那是什么规则?我将我的代码与其他自定义钩子进行了比较,没有区别。

useApiCall函数中,我剥离了所有逻辑并使用了单个逻辑useState并得到了相同的错误。我究竟做错了什么?

从(authActions)调用的钩子:https ://github.com/SMasood1/Chat-App/blob/main/client/src/context/authContext/authAction.js

自定义钩子(useApiCall):https ://github.com/SMasood1/Chat-App/blob/main/client/src/context/a

import { useState, useEffect, useReducer } from 'react';

// Can make this more elegant and able to handle different types of methods and headers

const FETCH_INIT = 'FETCH_INIT';
const FETCH_SUCCESS = 'FETCH_SUCCESS';
const FETCH_FAILURE = 'FETCH_FAILURE';

const dataReducer = (state, action) => {
  switch (action.type) {
    case FETCH_INIT:
      return {
        ...state,
        isLoading: true,
        isError: false
      }
    case FETCH_SUCCESS:
      return {
        ...state,
        isLoading: false,
        isError: false,
        data: action.payload
      }
    case FETCH_FAILURE:
      return {
        ...state,
        isLoading: false,
        isError: true,
        data: action.error
      }
    default:
      throw new Error();
  }
}
export const useApiCall = (initialUrl, initialMethod, initialData) => {
  const [state, dispatch] = useReducer(dataReducer, {
    isLoading: false,
    isError: null,
    data: initialData ? initialData : ''
  })

  const [method, setMethod] = useState(initialMethod ? initialMethod : null);
  const [url, setUrl] = useState(initialUrl ? initialUrl : '');
  useEffect(() => {
    const fetchData = async () => {
      await dispatch({ type: FETCH_INIT });
      let response;
      try {
        switch (method) {
          case 'GET':
            response = await fetch(url);
            break;
          case 'POST':
            response = await fetch(url, {
              method: method,
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify(state.data)
            });
            break;
          default:
            console.log('Incorrect HTTP Request Method');
        }
        if (response.ok) {
          let resBody = await response.json();
          dispatch({ type: FETCH_SUCCESS, payload: resBody });
        } else {
          let resBody = await response.json();
          dispatch({ type: FETCH_FAILURE, error: resBody });
        }
      } catch (error) {
        dispatch({ type: FETCH_FAILURE, error: 'Unable to send request!' });
      }
    }
    if (method && url) {
      fetchData();
    }
  }, [url, method, state.data]);
  return [state, setUrl, setMethod]
}

我收到的错误如下:

未捕获(承诺中)错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能由于以下原因之一而发生:

  1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 你可能在同一个应用程序中拥有多个 React 副本

标签: javascriptreactjs

解决方案


推荐阅读