【问题标题】:React Hook "useCategory" cannot be called inside a callback不能在回调中调用 React Hook “useCategory”
【发布时间】:2019-10-22 18:53:10
【问题描述】:

这是我的代码

import React, { FC, useState,useMemo } from "react";

const FormSearch: FC<{ params: string }> = ({
   params 
}) => {
  const [category, useCategory] = useState<string>("All");
  const [search, setSearch] = useState<string>("");
  useMemo(() => {             
     const searchParams = new URLSearchParams(params);
    if (!!searchParams.get("Categories")&&!!searchParams.get("Search")) {
          useCategory(`${searchParams.get("Categories")}`); 
          setSearch(`${searchParams.get("Search")}`);   
    } else {
      setSearch("");
      useCategory("All")
    }
  }, [params]);

  return (
    <div>1000</div>
  );
};

我收到这些错误

第 16 行:不能在回调中调用 React Hook “useCategory”。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用 react-hooks/rules-of-hooks 第 20 行:不能在回调中调用 React Hook “useCategory”。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数 react-hooks/rules-of-hooks 中调用

【问题讨论】:

  • 只能从 React 函数调用 React 钩子,无论是 React 函数组件还是自定义钩子。
  • @ Ulug Toprak 我违反了“不要在循环、条件或嵌套函数中调用钩子”的规则。 ??
  • @Ulug Toprak 我刚才写错了 useCategory 它是必要的 setCategory

标签: reactjs typescript


【解决方案1】:

你不应该使用 useCategory 来设置你的 category 状态,它会被 react 检测为它的钩子。将其重命名为setCategory 将解决您的问题

【讨论】:

    【解决方案2】:

    问题在于您将钩子放入条件中。

    根据文档,您应该这样做:

      useEffect(function persistForm() {
        // ? We're not breaking the first rule anymore
        if (name !== '') {
          localStorage.setItem('formData', name);
        }
      });
    

    当您创建具有内部条件的效果时。请记住,必须在组件的顶层调用 Hooks。

    您可以阅读更多关于它的信息here

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 2021-08-07
      • 2022-10-14
      • 2021-06-19
      • 2021-12-29
      • 2021-03-20
      • 1970-01-01
      • 2020-06-18
      • 2020-07-07
      相关资源
      最近更新 更多