【问题标题】:Invalid hook call when using useEffect使用 useEffect 时挂钩调用无效
【发布时间】:2020-01-07 16:35:32
【问题描述】:

我在尝试从我的 react 功能组件调度操作时收到此错误:

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

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

【问题讨论】:

  • 您是否尝试过将const dispatch = useDispatch(); 移动到组件中?

标签: reactjs typescript redux


【解决方案1】:

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

import React, { useEffect } from 'react';

type Props = {};

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

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2021-09-08
    • 1970-01-01
    • 2021-12-26
    相关资源
    最近更新 更多