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 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...