使用redux后,在组件中通过useSelector(state=>state.xxx)
拿数据的时候,就会报一个错误,内容就是 “类型"DefaultRootState"上不存在属性"xxx”"
解决
- 使用store.getState获取到所有redux中的数据
- TS中提供了
ReturnType
, 用于 获取函数类型的返回值类型 - 通过
typeof
将 反推出 获取到的数据类型,然后暴露出去使用
示例:
单独的声明一个 store.d.ts文件
import store from '@/store'
// Redux 应用的状态
export type RootState = ReturnType<typeof store.getState>
// ReturnType:thunk action 的返回类型,项目中几乎都是返回 Promise
这样子的话,在使用useSeletor
获取数据,就不会报类型的错误了
import { RootState } from '@/store/types/store'
import { useSelector } from 'react-redux'
const xxx = useSelector((state: RootState) => state.xxxx)
解决使用 dispatch类型错误
使用redux-thunk
后调用dispatch显示,没有指定dispatch的类型
解决
- 使用
redux-thunk
中提空的ThunkAction
方法 ThunkAction
需要提供四个泛型类型变量参数
示例:
import { ThunkAction } from 'redux-thunk'
export type RootThunkAction = ThunkAction<void, RootState, unknown, RootAction>
RootAction
为 相关的action类型声明
例如:
// 项目中所有 action 的类型
// type RootAction = LoginAction | ProfileAction
export type RootAction = LoginAction | ProfileAction
export type ProfileAction =
| {
type: 'profile/fetchUser'
payload: User
}
| {
type: 'profile/fetchUserProfile'
payload: UserProfile
}
RootState
为上面第一个问题中得到的类型
使用方式
- 声明了
RootAction
后,使用dispatch就有了参数的提示,再也不会写错了