首页 > 解决方案 > 使用 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 <></>;
};

标签: reactjstypescriptredux

解决方案


您将需要对功能组件使用 TypeScript 类型,并提供 props 作为通用类型的一部分。并且不要忘记导入所需的模块。

import React, { useEffect } from 'react';

type Props = {};

export const Keyboard: React.FC<Props> = () => {
  useEffect(() => document.addEventListener('keydown', ({ keyCode }) => dispatch(moveDown())));
  return <></>;
};

推荐阅读