【问题标题】:Call react hooks inside event handler在事件处理程序中调用反应挂钩
【发布时间】:2021-12-01 13:26:40
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs react-hooks event-handling fetch


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      正如错误所述,该问题违反了钩子规则(react-hooks/rules-of-hooks) 更多信息可以在这里找到: https://reactjs.org/docs/hooks-rules.html

      您只能在功能组件的顶层使用钩子,但handleClick() 函数会将钩子放在第二层而不是顶层。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-17
        • 1970-01-01
        • 2021-01-12
        • 2019-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-24
        相关资源
        最近更新 更多