首页 > 解决方案 > 在事件处理程序中调用反应钩子

问题描述

如果单击某个按钮,我需要重新获取数据,但是当我在单击处理程序中调用钩子时,出现以下错误

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 开头

标签: javascriptreactjsreact-hooksevent-handlingfetch

解决方案


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>
  );
};

推荐阅读