You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React函数组件调用useState出现Invalid hook call错误如何解决?

问题排查与修复方案

核心错误原因

  • 函数组件调用方式不符合规范:你在Animation组件内直接以普通函数的形式执行Theanim(anim),而没有用React要求的JSX标签语法<Theanim />渲染组件。只有用JSX调用时组件才会进入React的组件渲染上下文,直接执行函数会打破Hook调用规则,触发Invalid hook call报错。你的参考代码中使用<WishStick />的写法是正确的,本次问题就是没有沿用该规范导致的。
  • 组件导出语法不规范:export default Animation = (stars) => {}属于错误写法,你未提前声明Animation变量,会隐式创建全局变量,引发上下文异常。
  • 缺少视频播放完成的监听逻辑:没有给<video>标签绑定onEnded事件,无法实现播放完成后自动消失的需求。
  • useState未设置初始值:useState()无参数时初始值为undefined,默认不会渲染视频,不符合需求预期。
  • 按钮type属性设置不合理:无表单场景下使用type="submit"会触发默认的表单提交行为,建议改为type="button"。

修正后代码

Animation组件

import './App.css';
import React, { useState } from "react";
import Theanim from './AnimationPicker';
import pullanim from './wishfinal';

// 修正组件声明与导出写法
const Animation = (stars) => {
    // 设置初始值为true,默认显示视频
    const [displayed, setDisplayed] = useState(true);
    const anim = pullanim(stars);
    return(
        <div>
            {/* 以JSX语法渲染组件,传递参数与播放完成回调 */}
            { displayed && <Theanim anim={anim} onVideoEnd={() => setDisplayed(false)} />}
            <button className="closebutton" type="button" outline onClick={() => setDisplayed(false)}>Close</button>
        </div>
    );
}

export default Animation;

Theanim组件

// 解构props获取传入的参数
export default function Theanim({ anim, onVideoEnd }) {
    return(
        <div>
            {/* 绑定onEnded事件,实现播放完成触发回调 */}
            <video autoPlay muted className='pullanimation' onEnded={onVideoEnd}>
            <source src={anim} type="video/mp4" />
            Your browser does not support the video tag.
            </video>
        </div>
    );
}

内容的提问来源于stack exchange,提问作者Navraz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 22:15:04