Typescript如何为绑定指定action的useDispatch创建全局调用简写?
Redux useAppDispatch 简写方案
错误原因
- 参数不匹配报错:
useAppDispatch本身是无入参Hook,仅返回dispatch函数实例,直接传入action相关参数不符合其定义,触发参数校验错误。 - 顶层调用Hook报错:React Hook强制要求仅能在React函数组件、自定义Hook的顶层作用域调用,全局作用域调用不符合规则。
实现方案
单组件内快速简写
在组件内部直接封装触发方法即可,注意导入action creator时可重命名避免命名冲突:
import { edit as editAction } from '@/store/xxxSlice' import { useAppDispatch } from '@/store' function DemoComponent() { const dispatch = useAppDispatch() // 封装后直接调用 const edit = (payload) => dispatch(editAction(payload)) // 业务逻辑中调用 const handleSubmit = () => { edit({ id: 1, content: '修改内容' }) } }
全局封装避免重复声明
通过自定义Hook统一封装所有常用action的触发逻辑,一次封装所有组件通用:
- 首先编写自定义Hook:
// src/hooks/useActions.js import { useAppDispatch } from '@/store' import { bindActionCreators } from '@reduxjs/toolkit' // 导入所有需要封装的action creator import * as userActions from '@/store/userSlice' import * as articleActions from '@/store/articleSlice' export const useActions = () => { const dispatch = useAppDispatch() // 用Redux自带的bindActionCreators批量绑定,无需手动逐个封装 return { ...bindActionCreators(userActions, dispatch), ...bindActionCreators(articleActions, dispatch) } }
- 组件内直接使用:
import { useActions } from '@/hooks/useActions' function DemoComponent() { // 按需取出需要的触发方法 const { editUser, addArticle } = useActions() const handleEdit = () => { // 直接调用传参即可触发对应action editUser({ id: 2, nickName: '新昵称' }) } }
以上方案完全符合React Hook规则,不会出现报错,同时满足简写需求,TypeScript场景下也能完整继承action creator的类型定义,无需额外写类型声明。
内容的提问来源于stack exchange,提问作者Adomas Gaudiesius
相关产品推荐
相关产品推荐

