redux中间件之redux-thunk

为什么使用中间件?

在redux的actionCreators里面只能做一些同步的操作,reducer只能是个纯函数,也没办法进行操作,但是后续如果需要做一些异步请求,就没办法实现了。
此时就需要安装一些redux的中间件,来帮助我们实现异步操作,例如redux-thunk, redux-saga, redux-promise

redux的中间件?

它是在actionCreators创建的action到达reducer中间的过程。
可以利用Redux middleware 来进行日志的记录,创建崩溃报告,调用异步接口或者路由等。
redux-thunk就是增强了派发功能,store.dispatch(action)的增强。

中间件的使用

1.安装redux的中间件
  yarn add  redux-thunk
2.在store/index.js里面引入
  import {
      applyMiddleware, createStore } from 'redux';
  import thunk from 'redux-thunk';
  const store = createStore(
      reducer,
      applyMiddleware(thunk)
   );

引入完成之后,将thunk中间件放在applyMiddleware方法之中,就可以在actionCreators中进行一些异步的操作了。
例如:

 compute(){
             
    return dispatch=>{
                 
       setTimeout(()=>{
                     
           dispatch({
     type:COMPUTE})            
       },1000)        
    }   
 }

redux-thunk源码

在redux-thunk源码里:就会判断actionCreators是一个对象还是一个函数
如果是一个对象:内部会自动的调用dispatch(action)给reducer进行处理(同步)
actionCreators ==> 自动的调用dispatch(action) ==> reducer ==> 返回新状态的store ==> react组件view
如果是一个函数:内部就会提供一个参数dispatch,让我们自己选择对应的时机进行dispatch(action)给reducer处理。
actionCreators ==> middleware处理后 ==> 手动调用dispatch(action) ==> reducer ==> 返回新状态的store ==> react组件view

export function addCount() {
     
  return {
     type: ADD_COUNT}
} 
export function addCountAsync() {
     
  return dispatch => {
     
    setTimeout( () => {
     
      dispatch(addCount())
    },2000)
  }
}

redux-thunk源码:

function createThunkMiddleware(extraArgument) {
             
    return ({
      dispatch, getState }) => (next) => (action) => {
                
 	if (typeof action === 'function') {
                     
 	    return action(dispatch, getState, extraArgument);           
 	}           
  	return next(action);        
    };    
 }
    
const thunk = createThunkMiddleware();    
thunk.withExtraArgument = createThunkMiddleware;
    
export default thunk;

它是一种es6的写法:将它转换为es5的写法梗容易理解:

function createThunkMiddleware(extraArgument) {
     
  return function({
      dispatch, getState }) {
     
    return function(next){
     
      return function(action){
     
        if (typeof action === 'function') {
     
          return action(dispatch, getState, extraArgument);
        }
        return next(action);
      };
    }
  }
}

redux-thunk的操作,就是可以接受一个返回函数的action creator。如果这个action creator返回的是一个函数,就执行它,如果不是,就按照原来的next(action)执行。
下面就是redux-thunk中间件的action流程:
redux中间件之redux-thunk_第1张图片

你可能感兴趣的:(中间件,reactjs,html5,javascript)