You need to enable JavaScript to run this app. 在React子组件中调用useReducer的dispatch方法不生效该如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

在React子组件中调用useReducer的dispatch方法不生效该如何解决?

修复方案

核心调整点如下:

  • 把useReducer移到App组件内部,符合React Hook必须在组件顶层调用的规则
  • 补全状态更新函数的调用括号,确保状态可以正常触发更新
  • 给异步请求函数添加async关键字,并用useEffect包裹请求逻辑,避免重复触发接口调用
  • 调整按钮的结构逻辑,原代码中将整个页面容器和子组件都包裹在按钮内属于逻辑错误,已修正为按钮和子组件平级排布

App.tsx 代码

import { useReducer } from 'react';
import Button from '你的按钮组件引入路径';
import ChildComponent from './ChildComponent';

export default function App() {
  const [enableNotification, setEnableNotification] = useReducer((open) => !open, true);

  return (
    <div className="App">
      {/* 若需要控制按钮是否渲染,保留下方条件判断写法 */}
      {enableNotification && <Button>通知按钮</Button>}
      {/* 若需要控制按钮是否禁用,替换为下方写法即可 */}
      {/* <Button disabled={!enableNotification}>通知按钮</Button> */}
      <ChildComponent setEnableNotification={setEnableNotification} />
    </div>
  );
}

ChildComponent.tsx 代码

import { useEffect } from 'react';
import axiosInstance from '你的axios实例引入路径';
import Dialog from '你的弹窗组件引入路径';

// 替换any为具体props类型,更符合TS规范
export default function ChildComponent(props: { setEnableNotification: () => void }) {
    
  const getDetailsAPI = async () => {
    const result = await axiosInstance().get('替换为你的实际API地址');
    if(result.status === 200){
      if(result.data.length == 0){
        // 补全括号触发状态更新
        props.setEnableNotification();
      }
    }
  }

  // 组件挂载时调用一次接口,避免重复请求
  useEffect(() => {
    getDetailsAPI();
  }, []);

  return (
    <Dialog>
      <div className="App">
        {/* 弹窗内的业务内容 */}
      </div>
    </Dialog>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 05:06:11