javascript - 在事件处理程序中调用反应钩子
问题描述
如果单击某个按钮,我需要重新获取数据,但是当我在单击处理程序中调用钩子时,出现以下错误
const Menus = ({ menus, title }) => {
const handleClick = () => {
const { data: cartItems } = useFetch(API_URL + 'cart');
}
}
src\components\Menus.js | 第 26:13 行:React Hook "useFetch" 在函数 "handleMenu" 中被调用,该函数既不是 React 函数组件也不是自定义 React Hook 函数。React 组件名称必须以大写字母 react-hooks/rules-of-hooks 开头
解决方案
React 钩子不能在纯 JavaScript 函数中使用。它会打破钩子的规则。Hooks 只能在 React 函数组件中使用。返回 ReactElement 的函数将被视为 React 函数组件,而不是 JS 中的普通函数。
useFetch
您应该在钩子中返回数据和数据获取函数。以便您以后可以使用数据获取功能。
例如
import React from 'react';
import { useCallback, useEffect, useState } from 'react';
const API_URL = 'http://localhost:8080/api/';
const api = {
async getCartItems() {
return ['apple', 'banana'];
},
};
function useFetch(url: string) {
const [cartItems, setCartItems] = useState<string[]>([]);
// fetch data later use this function.
const getCartItems = useCallback(() => {
return api.getCartItems().then((res) => {
setCartItems(res);
});
}, [url]);
// fetch data when component mount
useEffect(() => {
getCartItems();
}, [url]);
return { data: cartItems, getCartItems };
}
const Menus = () => {
const { data: cartItems, getCartItems } = useFetch(API_URL + 'cart');
const handleClick = () => {
getCartItems();
};
return (
<div onClick={handleClick}>
<ul>
{cartItems.map((item, i) => {
return <li key={i}>{item}</li>;
})}
</ul>
</div>
);
};
推荐阅读
- html - 如何在打开和关闭短代码之间放置多行代码
- node.js - 如何解密在后端(nodejs)中加密的前端值?
- java - 在同一会话中更改实体管理器数据源
- java - 使用 Gradle 时如何忽略 Jacoco 中的内部静态类
- reactjs - 如何在 Drupal 8 中添加一个反应组件以使用分页列出节点
- python - 如何优化代码以迭代 dict 并将值存储在列表中?
- javascript - 在 reactjs 中通过不同的 id 从 api 获取数据
- oracle - 在 oracle 中将 oracle 查询输出转换为 xlsx ( excel ) 格式
- android - SYSTEM_ALERT_WINDOW 的运行时权限
- android - Firestore 数据库中的 getValue() 等价物是什么?