钩子叫有条件编译错误?


Line 15:3:  React Hook "useEventListener" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?  react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.

你好 当我尝试在local上运行以下代码时,我收到上述错误,但在线编辑器编译成功?为什么?

https://stackblitz.com/edit/react-8o8dib?file=index.js

import { useCallback } from 'react';
import useEventListener from './useEventListener';
const ESCAPE_KEY = 27;
const useEscape = (callback, disabled = false) => {
if (disabled) return;
const handleEscapePress = (event) => {
if (event.keyCode === ESCAPE_KEY) {
callback(event);
}
};
useEventListener('keydown', handleEscapePress);
};
export default useEscape;

我正在使用intellij webstrom.

问题

您有条件地提前返回,因此不会在每个渲染周期调用/调用useEventListener

溶液

似乎disabled用于禁止触发回调,因此请改为将条件放在该条件上。

import useEventListener from './useEventListener';
const ESCAPE_KEY = 27;
const useEscape = (callback, disabled = false) => {
const handleEscapePress = (event) => {
if (event.keyCode === ESCAPE_KEY) {
!disabled && callback(event);
}
};
useEventListener('keydown', handleEscapePress);
};
export default useEscape;

相关内容

  • 没有找到相关文章

最新更新