Redux React中SetCityAction无法赋值给UnknownAction问题求助
React+Redux调用dispatch时出现TypeScript类型错误的解决方法
问题代码
组件中的dispatch调用代码:
const dispatch = useDispatch(); const handleChange = (event: React.ChangeEvent<HTMLSelectElement>) => { const cityName = event.target.value; dispatch(setCity(cityName)); };
action定义代码:
import { SET_CITY } from './actionTypes'; // Define action interfaces interface SetCityAction { type: typeof SET_CITY; payload: string; } // Combine action types into a union type export type AppActions = SetCityAction | SetDataAction; // Define action creators export const setCity = (city: string): SetCityAction => ({ type: SET_CITY, payload: city, });
错误信息
Argument of type 'SetCityAction' is not assignable to parameter of type 'UnknownAction'. Index signature for type 'string' is missing in type 'SetCityAction'.
问题原因
TypeScript默认将useDispatch()的返回类型推断为Dispatch<UnknownAction>,而自定义的SetCityAction没有满足UnknownAction的类型约束(要求包含字符串索引签名),导致类型不兼容。本质是Redux的类型系统没有识别到你的自定义action类型。
解决方案
步骤1:在store文件中定义自定义Dispatch类型
从Redux store的dispatch属性推导正确的类型,示例代码:
// store.ts import { configureStore } from '@reduxjs/toolkit'; import rootReducer from './reducers'; export const store = configureStore({ reducer: rootReducer, }); // 导出适配当前store的dispatch类型 export type AppDispatch = typeof store.dispatch;
步骤2:在组件中指定useDispatch的类型
导入AppDispatch并在调用useDispatch时显式声明类型:
import { useDispatch } from 'react-redux'; import { AppDispatch } from './store'; import { setCity } from './actions'; // ... const dispatch = useDispatch<AppDispatch>(); const handleChange = (event: React.ChangeEvent<HTMLSelectElement>) => { const cityName = event.target.value; dispatch(setCity(cityName)); };
可选优化:封装自定义useDispatch Hook
为了避免每次使用都重复指定类型,可以封装一个全局自定义Hook:
// hooks.ts import { useDispatch } from 'react-redux'; import type { AppDispatch } from './store'; export const useAppDispatch = () => useDispatch<AppDispatch>();
之后在组件中直接使用这个Hook:
const dispatch = useAppDispatch();
额外注意事项
检查代码中SetDataAction是否已经正确定义,因为AppActions是它和SetCityAction的联合类型,未定义的话可能会引发额外的类型问题。
内容的提问来源于stack exchange,提问作者robot
相关产品推荐
相关产品推荐

