[英]How to disable React Hook “useCallback” cannot be called inside a callback warning?
I have created a utility hook that allow updating the state of components as long as they are mounted.我创建了一个实用程序挂钩,只要它们被安装,它就允许更新组件的状态。
to do so, I had to call useCallack
inside the callback function of Array.map
为此,我必须在
useCallack
的回调函数中Array.map
this is my code这是我的代码
export const useSafeDispatches = (...dispatches) => {
const mounted = useRef(false);
useLayoutEffect(() => {
mounted.current = true;
return () => (mounted.current = false);
}, []);
return dispatches.map((dispatch) =>
useCallback((...args) => (mounted.current ? dispatch(...args) : void 0), [dispatch])
);
};
I am getting this error when I try to build React Hook "useCallback" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
当我尝试构建
React Hook "useCallback" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
时出现此错误React Hook "useCallback" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
React Hook "useCallback" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
The error message says exactly what you need to do, pull useCallback
out of the map
callback.错误消息准确地说
useCallback
您需要做什么,将useCallback
从map
回调中拉出。 Your callback depends on the value of mounted.current
, so we make sure to include it in our list of dependencies -您的回调取决于
mounted.current
的值,因此我们确保将其包含在我们的依赖项列表中 -
export const useSafeDispatches = (...dispatches) => {
const mounted = useRef(false);
useLayoutEffect(() => {
mounted.current = true;
return () => (mounted.current = false);
}, []);
const safeDispatch = useCallback(dispatch =>
(...args) => mounted.current ? dispatch(...args) : void 0
, [mounted.current]);
return dispatches.map(safeDispatch);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.