一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情。
十分钟学会在TypeScript里写redux里的Hooks
useSelector的基本使用
// 获取todos数据
const todos = useSelector( state => state.todos) // 这里会报错,因为ts不知道state里有todos
useSelector接收两个泛型参数
第一个泛型类型:TState的默认值是DefaultRootState(就是{})用于指定state的类型
第二个泛型类型:TSelected用于指定返回值的类型
export function useSelector<TState = DefaultRootState, TSelected = unknown>(
selector: (state: TState) => TSelected,
equalityFn?: (left: TSelected, right: TSelected) => boolean
): TSelected;
解决方法一、
指定泛型类型
const todos = useSelector<{todos:[]} ,{id:number, name:string,isDone:boolean}[]>(state => state.todos)
console.log(todos)
解决方法二、
直接指定回调函数的形参类型
指定参数state是一个对象,里面有todos对象,并且todos里的属性名和类型指定好
const todos = useSelector((state: {todos:{id:number, name:string,isDone:boolean}[]}) => state.todos)
这种方法太麻烦,并且我们的项目会有很多模块,这样一个个指定根本不行,所以要用typeof和ReturnType这两个工具类型配合使用
typeof和ReturnType配合获取RootState的类型
typeof可以获取某个数据的类型
function fn(n1: number, n2:number):number {
return n1 + n2
}
// 获取fn函数的类型。这里鼠标悬浮提示就能看到
type Fn = typeof fn
ReturnType是一个泛型工具类型,可以获取函数类型的返回值的类型
格式
type 返回值的类型 = ReturnType<函数f的类型>
示例
function fn(n1: number, n2:number):number {
return n1 + n2
}
// 获取fn函数的类型
type Fn = typeof fn
// 获取Fn函数的返回值类型
type Res = ReturnType<Fn> // 鼠标悬浮查看提示
获取RootState的类型-实操
在store/index.ts中定义RootState类型并导出
export type RootState = ReturnType<typeof store.getState>
在业务组件中导入使用 import { RootState } from '../store'
// 获取todos数据
const todos = useSelector((state: RootState) => state.todos)
usedispatch的使用
useDispatch可以接收一个泛型参数用于指定Action的类型
import { Dispatch } from "react"
import { useSelector, useDispatch } from "react-redux"
import { RootStateType } from '../store'
export default function Home() {
const dispatch = useDispatch<Dispatch<{type:string,payload:any}>>()
dispatch({
type: 'abc',
payload: 123
})