reactjs - 使用 useEffect 时挂钩调用无效
问题描述
尝试从我的反应功能组件调度操作时出现此错误:
Invalid hook call. Hooks can only be called inside of the body of a function component
这个 React 组件不渲染任何东西,只是监听页面上的 keypress 事件
import { useDispatch } from 'react-redux';
const dispatch = useDispatch();
const {
actions: { moveDown }
} = gameSlice;
type Props = {};
export const Keyboard = ({}: Props) => {
useEffect(() => document.addEventListener('keydown', ({ keyCode }) => dispatch(moveDown())));
return <></>;
};
解决方案
您将需要对功能组件使用 TypeScript 类型,并提供 props 作为通用类型的一部分。并且不要忘记导入所需的模块。
import React, { useEffect } from 'react';
type Props = {};
export const Keyboard: React.FC<Props> = () => {
useEffect(() => document.addEventListener('keydown', ({ keyCode }) => dispatch(moveDown())));
return <></>;
};
推荐阅读
- android - Android 通知:数据和消息
- javascript - 获取对象数组中的特定数据并删除其行(条带化谷歌应用脚本)
- amazon-web-services - 如何将特定文件夹从 AWS S3 挂载到 ec2 实例
- flutter - 如何在flutter默认日期选择器小部件中删除时间戳并仅从日期选择器中获取日期
- jquery - Kendo UI:标签条内的网格标题(宽度)对齐问题
- regex - .htaccess 重写正则表达式:匹配任何内容,但不得影响其他规则
- java - 如何在java中查看exe的退出状态
- latex - 如何使用 doxygen 生成带有自定义乳胶样式表和命令的 pdf?
- ms-access - 字符串到时间戳的转换
- java - 在java jdk8中将UTC日期转换为本地日期(服务器的时区)