简体   繁体   English

使用 useEffect 时钩子调用无效

[英]Invalid hook call when using useEffect

I get this error when trying to dispatch an action from my react functional component:尝试从我的反应功能组件分派动作时出现此错误:

Invalid hook call. Hooks can only be called inside of the body of a function component

This React component does not render anything just listen to keypress event on the page这个 React 组件不会渲染任何东西,只是监听页面上的按键事件

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 <></>;
};

You will need to use the TypeScript typings for functional components, and provide the props as part of the generic typings.您将需要对功能组件使用 TypeScript 类型,并提供道具作为通用类型的一部分。 And don't forget to import the required modules.并且不要忘记导入所需的模块。

import React, { useEffect } from 'react';

type Props = {};

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM