javascript - 在自定义钩子中使用钩子时触发的钩子错误使用无效?
问题描述
我需要有关自定义挂钩的帮助。我创建了一个自定义挂钩来进行 api 调用(useApiCall),我从我的authActions.js文件中调用它,以将用户名和密码发送到服务器以注册新用户。我收到一条错误消息,提示我想念在useApiCall功能组件中使用钩子。
当我删除useApiCalluseReducer
功能组件中的逻辑时,它说我误用了. 它不会让我在 React 功能组件中使用钩子。useState
useReducer
useApiCall
我知道我违反了钩子规则,但那是什么规则?我将我的代码与其他自定义钩子进行了比较,没有区别。
在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]
}
我收到的错误如下:
未捕获(承诺中)错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能由于以下原因之一而发生:
- 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 您可能违反了 Hooks 规则
- 你可能在同一个应用程序中拥有多个 React 副本
解决方案
推荐阅读
- vb6 - 在 IDE 中多选控件时出现奇怪的溢出
- r - 组合条形图修改 R 中的 x 轴刻度标签
- php - 更改主机密码后无法连接到 mysql 服务器
- apache-spark - Spark 的 df.cache() 是急切执行还是懒惰执行?
- python-3.x - 无效的语法 (:) Python 3.6.5
- google-cloud-platform - 如何将抢占式 GPU 和 SSD 添加到 GCloud 实例
- javascript - Chrome.tabs.executeScript(); + .addEventListener("点击", ...); 通过 chrome 扩展将代码注入活动网页
- angular - 是否可以刷新 Angular 2 对话框而不是它的父项?
- javascript - 如何将重定向 URL 返回到我的 Chrome 扩展弹出窗口?
- azure - 集合(Edm.String)属性中的 Azure 搜索索引数据