Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用redux工具包键入中间件_Reactjs_Typescript_Redux_Redux Toolkit - Fatal编程技术网

Reactjs 使用redux工具包键入中间件

Reactjs 使用redux工具包键入中间件,reactjs,typescript,redux,redux-toolkit,Reactjs,Typescript,Redux,Redux Toolkit,我正在使用TypeScript和redux工具包开发一个webapp tl;dr 如何在中间件上设置dispatch参数的类型 我需要从我的服务器获取一些数据并将其保存在我的存储中。因此,我编写了一个类似于bellow(简化)的代码: 请注意,因为获取数据是一项异步任务,所以我不能将其直接放在setPrices上。因此,我创建了一个名为fetchPrices的中间件来执行请求任务并调用setPrices 尽管它可以工作,但我对这个解决方案不满意,因为我设置了any类型。如何正确设置更好的类型?

我正在使用TypeScript和
redux工具包
开发一个webapp

tl;dr

如何在中间件上设置
dispatch
参数的类型


我需要从我的服务器获取一些数据并将其保存在我的存储中。因此,我编写了一个类似于bellow(简化)的代码:

请注意,因为获取数据是一项异步任务,所以我不能将其直接放在
setPrices
上。因此,我创建了一个名为
fetchPrices
的中间件来执行请求任务并调用
setPrices

尽管它可以工作,但我对这个解决方案不满意,因为我设置了
any
类型。如何正确设置更好的类型?我找不到从
redux toolkit
导入
ThunkDispatch
的方法


有更好的方法吗?

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 }))
  }
使用的是store.dispatch的
类型,因为Redux Toolkit的
store.dispatch
已经包括
ThunkDispatch
。(如果您使用额外的中间件,并将所有东西都放在中心位置,那么您可以扩展
store.dispatch


此外,还请看一下Redux工具包的功能。如果您遗漏了任何重要内容,请打开一个问题并让我们知道:)

谢谢,但我找到了另一个使用挂钩执行异步任务的解决方案=]
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 }))
  }