彻底学会redux-thunk在TypeScript中的使用

620 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第N天,点击查看活动详情

1、引入redux-thunk

import thunk from 'redux-thunk'
const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))

在action中补充获取数据的action

export function getTodos() {
return async (dispatch:any) => {
const res = await axios.get('https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/todos')

// 异步操作
dispatch({
  type: 'INIT_TODO',
  data: res.data.data
})
}
 }

在对应组件调用

useEffect(() => {
    dispatch(getTodos())
  }, [dispatch])

thunk类型的变更,使用了thunk之后,返回的Action类型不再是对象,而是函数类型的Action,因此需要修改Action的类型。ThunkAction类型的使用

参考地址redux.js.org/usage/usage…

// 类型参数1:ReturnType 用于指定函数的返回值类型 void
// 类型参数2: 指定RootState的类型
// 类型参数3: 指定额外的参数类型,一般为unkonwn或者any
// 类型参数4: 用于指定dispatch的Action类型
// 修改删除Action
export function delTodo(id: number): ThunkAction<void, RootState, unknown, TodoAction> {
return (dispatch) => {
setTimeout(() => {
  dispatch({
    type: 'DEL_TODO',
    id,
  })
}, 1000)
}
}

但我们一般更推荐抽到store/index.ts下面

import { createStore } from "redux"
import RootReducer from './reducer'
import thunk, { ThunkAction } from 'redux-thunk'
import { applyMiddleware } from 'redux'
import { composeWithDevTools } from "redux-devtools-extension"
const store = createStore(RootReducer,  composeWithDevTools(applyMiddleware(thunk)))
export type RootStateType = ReturnType<typeof store.getState>//获取所有的state类型  
定义所有action的类型
export type ActionsType =
| { type: 'UPDATE'; id: number }
| { type: 'DEl'; id: number }
| { type: 'ADD'; payload: TodoType }
| { type: 'INIT'; payload: TodoType[] }
export type RootThunkAction = ThunkAction<void, RootStateType, unknown, TodoAction>
export type RootThunkAction = ThunkAction<void, RootState, unknown, ActionsType> 

然后只需要在action中导入RootThunkAction即可,定义为函数的返回值类型

redux-thunk版本bug

在redux-thunk@2.4.0新版中,使用dispatch的时候,会丢失提示,需要降级到2.3.0版本

github.com/reduxjs/red…

npm i redux-thunk@2.3.0

参考:www.npmjs.com/package/red…