【发布时间】:2020-03-29 13:50:03
【问题描述】:
我正在使用 TypeScript 和 redux-toolkit 开发一个 webapp。
tl;dr
如何在中间件上设置dispatch参数的类型?
我需要从我的服务器获取一些数据并将其保存在我的商店中。所以我写了如下代码(简化):
import { createSlice } from '@reduxjs/toolkit'
import { TNewOrder } from '../store'
const initialState: TNewOrder = {
prices: [],
// other stuffs...
}
const newOrderSlice = createSlice({
initialState,
name: 'new-order',
reducers: {
setPrices(state, action) {
const { payload } = action
return {
...state,
prices: payload.prices
}
},
updateFormData(state, action) {
// not important...
}
}
})
const { setPrices, updateFormData } = newOrderSlice.actions
const fetchPrices = () =>
async (dispatch: any) => {
const response = await fetch('https://jsonbox.io/box_4186ae80994ed3789969/prices/5de7e570de45ab001702a382')
const { prices } = await response.json()
dispatch(setPrices({ prices }))
}
export { fetchPrices, updateFormData }
export default newOrderSlice.reducer
请注意,因为获取数据是一个异步任务,所以我不能将它直接放在setPrices 上。于是我创建了一个叫fetchPrices的中间件来做请求任务并调用setPrices。
尽管它有效,但我对这个解决方案不满意,因为我设置了 any 类型。如何正确设置更好的类型?我找不到从redux-toolkit 导入ThunkDispatch 的方法。
有没有更好的方法?
【问题讨论】:
标签: reactjs typescript redux redux-toolkit