Redux中间件的使用

Redux Middleware

Redux中间件是一种增强 store.dipatch 方法的函数,常见的中间件如:

  • redux-thunk
  • redux-promise

什么是thunk?

thunk用来描述一种函数,它被另一个函数return

function wrapper_function() {
  // 下面的函数就是thunk,它会被延迟调用
  return function thunk() {   // thunk函数可以任意命名或直接使用匿名
    console.log('do stuff now');
  };
}
//调用thunk
wrapper_function()();

redux-thunk

增强效果:允许action creators返回一个函数,这个函数可以被dispatch

/*
	一般的action creator返回的是一个明确的action对象
*/
function increment() {
  return {
    type: INCREMENT_COUNTER,
  };
}

/*
	增强的action creator返回的是一个thunk函数
	- 该函数接收 dispatch 和 getState 作为形参
	- 该函数非纯函数,可以使用如异步方法、api请求、条件调用等副作用操作
*/
function incrementAsync() {
  return (dispatch) => {
    setTimeout(() => {
      dispatch(increment());
    }, 1000);
  };
}
function incrementIfOdd() {
  return (dispatch, getState) => {
    const { counter } = getState();
    if (counter % 2 === 0) {
      return;
    }
    dispatch(increment());
  };
}

利用redux-thunk使action creator返回一个发送异步请求的thunk函数

function logOutUser() {
  return function(dispatch, getState) {
    return axios.post('/logout').then(function() {
      // 假设已经创建了名为userLoggedOut的action creator
      dispatch(userLoggedOut());
    });
  };
}

//调用,返回的是一个Promise,可以继续.then
store.dispatch(logOutUser());
//在组件中调用
this.props.dispatch(logOutUser());
applyMiddleware

Redux多个中间件可以组合使用,以链式的方式逐个调用,各自相互独立,互不影响

在创建store时引入中间件

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

const store = createStore(rootReducer, applyMiddleware(thunk));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值