在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
相关产品推荐
相关产品推荐

