这是我的代码
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>
);
};
Run Code Online (Sandbox Code Playgroud)
我收到这些错误
第 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
问题在于您将钩子置于条件中。
根据文档,您应该执行以下操作:
useEffect(function persistForm() {
// We're not breaking the first rule anymore
if (name !== '') {
localStorage.setItem('formData', name);
}
});
Run Code Online (Sandbox Code Playgroud)
当您正在创建具有内部条件的效果时。请记住,必须在组件的顶层调用 Hook。