redux-thunk中文

thunk是redux解决异步的中间件。

我们为什么要使用redux-thunk这个中间件呢?

如果你不确定是否需要使用,那就不要用了(redux也是这个原则)

为啥会有redux-thunk这个东西呢

redux-thunk中间件可以允许你写的action creator函数可以返回action对象的同时,也可以返回一个函数。这个中间件可以被用来延缓分发action的时机,或者实现只在满足某个条件的时候才触发action。内部函数dispatch和getState作为参数。
<!-- more -->
下面是一个action生产函数返回一个函数实现异步的dispatch:

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);
  };
}

下面是action生产函数返回一个函数实现按照条件决定是否分发action

function incrementIfOdd() {
  return (dispatch,getState) => {
    const { counter } = getState();

    if (counter % 2 === 0) {
      return;
    }

    dispatch(increment());
  };
}

那么啥是thunk呢

thunk本质上是一个函数,它包裹一个表达式,使表达式的计算可以被推迟。

// 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;

安装

npm install --save redux-thunk

为了使redux-thunk生效,我们需要调用applyMiddleware():

import { createStore,applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,applyMiddleware(thunk)
);

实例

todo~~

资源推荐

阮一峰 redux中间件与异步操作
xixi 小站

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...