# Redux Thunk
Thunk [middleware](https://redux.js.org/tutorials/fundamentals/part-4-store#middleware) for Redux. It allows writing functions with logic inside that can interact with a Redux store's `dispatch` and `getState` methods.
For complete usage instructions and useful patterns, see the [Redux docs **Writing Logic with Thunks** page](https://redux.js.org/usage/writing-logic-thunks).
![GitHub Workflow Status](https://img.shields.io/github/workflow/status/reduxjs/redux-thunk/Tests)
[![npm version](https://img.shields.io/npm/v/redux-thunk.svg?style=flat-square)](https://www.npmjs.com/package/redux-thunk)
[![npm downloads](https://img.shields.io/npm/dm/redux-thunk.svg?style=flat-square)](https://www.npmjs.com/package/redux-thunk)
## Installation and Setup
### Redux Toolkit
If you're using [our official Redux Toolkit package](https://redux-toolkit.js.org) as recommended, there's nothing to install - RTK's `configureStore` API already adds the thunk middleware by default:
```js
import { configureStore } from '@reduxjs/toolkit'
import todosReducer from './features/todos/todosSlice'
import filtersReducer from './features/filters/filtersSlice'
const store = configureStore({
reducer: {
todos: todosReducer,
filters: filtersReducer
}
})
// The thunk middleware was automatically added
```
### Manual Setup
If you're using the basic Redux `createStore` API and need to set this up manually, first add the `redux-thunk` package:
```sh
npm install redux-thunk
yarn add redux-thunk
```
The thunk middleware is the default export.
<details>
<summary><b>More Details: Importing the thunk middleware</b></summary>
If you're using ES modules:
```js
import thunk from 'redux-thunk' // no changes here ð
```
If you use Redux Thunk 2.x in a CommonJS environment,
[donât forget to add `.default` to your import](https://github.com/reduxjs/redux-thunk/releases/tag/v2.0.0):
```diff
- const thunk = require('redux-thunk')
+ const thunk = require('redux-thunk').default
```
Additionally, since 2.x, we also support a
[UMD build](https://unpkg.com/redux-thunk/dist/redux-thunk.min.js) for use as a global script tag:
```js
const ReduxThunk = window.ReduxThunk
```
</details>
Then, to enable Redux Thunk, use
[`applyMiddleware()`](https://redux.js.org/api/applymiddleware):
```js
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './reducers/index'
const store = createStore(rootReducer, applyMiddleware(thunk))
```
### Injecting a Custom Argument
Since 2.1.0, Redux Thunk supports injecting a custom argument into the thunk middleware. This is typically useful for cases like using an API service layer that could be swapped out for a mock service in tests.
For Redux Toolkit, the `getDefaultMiddleware` callback inside of `configureStore` lets you pass in a custom `extraArgument`:
```js
import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './reducer'
import { myCustomApiService } from './api'
const store = configureStore({
reducer: rootReducer,
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
thunk: {
extraArgument: myCustomApiService
}
})
})
// later
function fetchUser(id) {
// The `extraArgument` is the third arg for thunk functions
return (dispatch, getState, api) => {
// you can use api here
}
}
```
If you need to pass in multiple values, combine them into a single object:
```js
const store = configureStore({
reducer: rootReducer,
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
thunk: {
extraArgument: {
api: myCustomApiService,
otherValue: 42
}
}
})
})
// later
function fetchUser(id) {
return (dispatch, getState, { api, otherValue }) => {
// you can use api and something else here
}
}
```
If you're setting up the store by hand, the named export `withExtraArgument()` function should be used to generate the correct thunk middleware:
```js
const store = createStore(reducer, applyMiddleware(withExtraArgument(api)))
```
## Why Do I Need This?
With a plain basic Redux store, you can only do simple synchronous updates by
dispatching an action. Middleware extends the store's abilities, and lets you
write async logic that interacts with the store.
Thunks are the recommended middleware for basic Redux side effects logic,
including complex synchronous logic that needs access to the store, and simple
async logic like AJAX requests.
For more details on why thunks are useful, see:
- **Redux docs: Writing Logic with Thunks**
https://redux.js.org/usage/writing-logic-thunks
The official usage guide page on thunks. Covers why they exist, how the thunk middleware works, and useful patterns for using thunks.
- **Stack Overflow: Dispatching Redux Actions with a Timeout**
http://stackoverflow.com/questions/35411423/how-to-dispatch-a-redux-action-with-a-timeout/35415559#35415559
Dan Abramov explains the basics of managing async behavior in Redux, walking
through a progressive series of approaches (inline async calls, async action
creators, thunk middleware).
- **Stack Overflow: Why do we need middleware for async flow in Redux?**
http://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux/34599594#34599594
Dan Abramov gives reasons for using thunks and async middleware, and some
useful patterns for using thunks.
- **What the heck is a "thunk"?**
https://daveceddia.com/what-is-a-thunk/
A quick explanation for what the word "thunk" means in general, and for Redux
specifically.
- **Thunks in Redux: The Basics**
https://medium.com/fullstack-academy/thunks-in-redux-the-basics-85e538a3fe60
A detailed look at what thunks are, what they solve, and how to use them.
You may also want to read the
**[Redux FAQ entry on choosing which async middleware to use](https://redux.js.org/faq/actions#what-async-middleware-should-i-use-how-do-you-decide-between-thunks-sagas-observables-or-something-else)**.
While the thunk middleware is not directly included with the Redux core library,
it is used by default in our
**[`@reduxjs/toolkit` package](https://github.com/reduxjs/redux-toolkit)**.
## Motivation
Redux Thunk [middleware](https://redux.js.org/tutorials/fundamentals/part-4-store#middleware)
allows you to write action creators that return a function instead of an action.
The thunk can be used to delay the dispatch of an action, or to dispatch only if
a certain condition is met. The inner function receives the store methods
`dispatch` and `getState` as parameters.
An action creator that returns a function to perform asynchronous dispatch:
```js
const INCREMENT_COUNTER = 'INCREMENT_COUNTER'
function increment() {
return {
type: INCREMENT_COUNTER
}
}
function incrementAsync() {
return dispatch => {
setTimeout(() => {
// Yay! Can invoke sync or async actions with `dispatch`
dispatch(increment())
}, 1000)
}
}
```
An action creator that returns a function to perform conditional dispatch:
```js
function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState()
if (counter % 2 === 0) {
return
}
dispatch(increment())
}
}
```
## Whatâs a thunk?!
A [thunk](https://en.wikipedia.org/wiki/Thunk) is a function that wraps an
expression to delay its evaluation.
```js
// calculation of 1 + 2 is immediate
// x === 3
let x = 1 + 2
// calculation of 1 + 2 is delayed
// foo can be called later to perform the calculation
// foo is a thunk!
let foo = () => 1 + 2
```
The term [originated](https://en.wikipedia.org/wiki/Thunk#cite_note-1) as a
humorous past-tense version of "think".
## Composition
Any return value from the inner function will be available as the return value
of `dispatch` itself. This is convenient for orchestrating an asynchronous
control flow with thunk action creators dispatching each other a
redux-thunk-3.0.0-beta.0.zip
需积分: 0 115 浏览量
更新于2024-08-31
收藏 897KB ZIP 举报
Redux 的 Thunk 中间件。它允许编写带有内部逻辑的函数,这些函数可以与 Redux 存储的 dispatch 和 getState 方法交互。
a3737337
- 粉丝: 0
- 资源: 2869
最新资源
- 信捷XC PLC与力士乐VFC-x610变频器通讯程序原创可直接用于生产的程序,程序带注释,并附送触摸屏程序,有接线方式和设置,通讯地址说明等 程序采用轮询,可靠稳定 器件:信捷XC3的PLC,博世
- CMIP6 变量详细表格
- KF2EDGK系列5.08接线端子,带3D封装
- 信捷XC PLC与3台力士乐VFC-x610变频器通讯通讯 原创可直接用于生产的程序,程序带注释,并附送触摸屏程序,有接线方式和设置,通讯地址说明等 程序采用轮询,可靠稳定 器件:信捷XC3的PLC
- org.xmind.ui.mindmap-3.6.1.jar
- 16台搅拌机定时控制程序16台搅拌机定时控制,使用三菱FX系列PLC,威伦通触摸屏,具备完善的控制功能
- 微网双层优化模型matlab 采用yalmip编写三个微网的分层优化模型,考虑电价的负荷响应,综合配电网运营商收益和用户购电成本,程序运行稳定
- rv1126交叉编译工具链gcc-arm-8.3-2019.02-x86-64-arm-linux-gnueabihf.tar.xz和安装步骤
- 1960-2023年世界各国国民总收入数据
- 风储深度调峰模型matlab 考虑风储的调峰模型,采用cplex作为求解器,实现不同主体出力优化控制,程序运行稳定,有参考资料,
- 计算机系统安全性与性能评估:IOMMU在Linux环境下的性能研究及其优化策略
- 电动汽车蒙特卡洛分析matlab 通过matlab程序编写电动汽车蒙特卡洛模型,得到汽车行驶里程的概率分布曲线和充电功率曲线,程序运行可靠,有参考资料
- 考虑交通流量的电动汽车充电站规划matlab 程序采用matlab编制,采用粒子群算法,结合交通网络流量,得到最终充电站规划方案,程序运行可靠
- rustdesk-1.3.6-x86-64.msi
- 电动汽车优化模型matlab 狼群算法
- 你还在为伺服驱动器 FPGA架构苦恼吗,本方案FPGA代码实现电流环 速度环 位置环 SVPWM 坐标变 测速 分频 滤波器等,程序方便移植不同的平台,具有很高的研究价值