【发布时间】:2020-07-11 23:01:20
【问题描述】:
我正在尝试在异步函数中调用 useState,例如:
const [searchParams, setSearchParams] = useState({});
const fetchData = () => useCallback(
() => {
if (!isEmpty(searchParams)) {
setIsLoading(true); // this is a state hook
fetchData(searchParams)
.then((ids) => {
setIds(ids); // Setting the id state here
}).catch(() => setIsLoading(false));
}
},
[],
);
我试图在此 fetchData 函数中设置两种状态(setIsLoading 和 setIds),但每当执行此函数时都会出现错误:
未捕获的错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。这可能由于以下原因之一而发生: 1. React 和渲染器的版本可能不匹配(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能在同一个应用中拥有多个 React 副本
我在这里打破的钩子规则是什么? 有没有办法从函数中设置这些状态?
PS:我这里只使用了useCallback钩子来调用这个函数lodash/debounce
编辑:该函数在useEffect 内部调用,如:
const debouncedSearch = debounce(fetchSearchData, 1000); // Is this the right way to use debounce? I think this is created every render.
const handleFilter = (filterParams) => {
setSearchParams(filterParams);
};
useEffect(() => {
console.log('effect', searchParams); // {name: 'asd'}
debouncedSearch(searchParams); // Tried without passing arguments here as it is available in state.
// But new searchParams are not showing in the `fetchData`. so had to pass from here.
}, [searchParams]);
【问题讨论】:
-
问题在于 useCallback 而不是 useState;因为你在函数内部调用它,这违反了钩子规则
-
你是如何使用 fetchData 的?
-
@MohamedELAYADI 添加了如何使用函数的示例代码。
-
你检查我提出的答案了吗?我将尝试对其进行更新以使其与去抖值一起使用
标签: reactjs react-hooks