【问题标题】:Typing middleware with redux-toolkit使用 redux-toolkit 键入中间件
【发布时间】: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


    【解决方案1】:

    ThunkDispatch 不是由@reduxjs/toolkit 导出的。如果你想使用它,你应该从redux-thunk 导入它。

    import { ThunkDispatch } from 'redux-thunk'; 
    
    const fetchPrices = () =>
      async (dispatch: ThunkDispatch) => {
        const response = await fetch('https://jsonbox.io/box_4186ae80994ed3789969/prices/5de7e570de45ab001702a382')
        const { prices } = await response.json()
    
        dispatch(setPrices({ prices }))
      }
    

    【讨论】:

      【解决方案2】:

      official suggestion 是使用typeof store.dispatch,因为 Redux-Toolkit 的store.dispatch 已经包含了ThunkDispatch。 (如果您使用额外的中间件并将所有内容都放在一个中心位置,您可以扩展 store.dispatch。)

      另外,还请看一下 Redux-Toolkit 的TypeScript documentation。如果您遗漏了任何重要的内容,请打开一个问题并告诉我们:)

      【讨论】:

      • 谢谢,但我找到了另一种使用钩子执行异步任务的解决方案 =]
      猜你喜欢
      • 1970-01-01
      • 2021-09-21
      • 2022-11-12
      • 2022-07-16
      • 2020-04-24
      • 2021-10-08
      • 2021-11-03
      • 2021-04-15
      • 2021-08-02
      相关资源
      最近更新 更多