Redux异步中间件

曾前端的刷新是以Ajax的出现为分水岭,当代运用中绝大部分页面衬着会以异步流的体式格局举行。在Redux中,假如要提议异步要求,最合适的位置是在action creator中完成。但我们之前相识到的action都是同步状况,因而须要引入中间件让action支撑异步状况,如异步action(异步要求)为一个函数,或许应用promise来完成,或许是其他自定义的情势等等,下面的middleware就是用来处置惩罚这些差别异步action(或许说成actionCreator)的.别的,在Redux社区里另有其他一些处置惩罚异步的中间件,它们迥然差别,这里就不逐一剖析了。

redux-thunk

redux-thunk 是 redux 官方文档中用到的异步组件,本质就是一个 redux 中间件,thunk 简朴来讲 就是一个封装表达式的函数,封装的目标是耽误实行表达式。

redux-thunk 是一个通用的处理方案,其中心头脑是让 action 可以变成一个 thunk ,如许的话:

  1. 同步状况:dispatch(action)
  2. 异步状况:dispatch(thunk)

    thunk 本质上就是一个函数,函数的参数为 dispatch, 所以一个简朴的 thunk 异步代码就是以下:

    this.dispatch(function (dispatch){
        setTimeout(() => {
           dispatch({type: 'THUNK_ACTION'}) 
        }, 1000)
    })

之前已讲过,如许的设想会致使异步逻辑放在了组件中,处理办法为笼统出一个 asyncActionCreator, 这里也一样,我们就叫 thunkActionCreator 吧,上面的例子可以改成:

export function createThunkAction(payload) {
    return function(dispatch) {
        setTimeout(() => {
           dispatch({type: 'THUNK_ACTION', payload: payload}) 
        }, 1000)
    }
}
// someComponent.js
this.dispatch(createThunkAction(payload))

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;

思绪:当action为函数的时刻,我们并没有挪用next或dispatch要领,而是返回action的挪用。这里的action即为一个Thunk函数,以到达将dispatch和getState参数通报到函数内的作用。

此时,action可以写成thunk情势(ThunkActionCreator):

function getweather(url,params){
  return (dispatch,getState)=>{
    fetch(url,params)
       .then(result=>{
          dispatch({
          type:'GET_WEATHER_SUCCESS',
          payload:result,
          });
     })
     .catch(err=>{
        dispatch({
            type:'GET_WEATHER_ERROR',
            error:err,
            });
      });
};
}

redux-promise

实在 thunk 我们已有了处置惩罚异步的才能, 然则每次我们要本身去手动触发三个 action, 工作量照样很大的。如今 ajax 许多都邑包装为 promise 对象,,异步要求实在都是应用promise来完成的 因而我们可以对与 dispatch 增添一层推断, 使得它具有处置惩罚具有 promise 属性的 action 的才能。

import {isFSA} from 'flux-standard-action';

function isPromise(val){
  return next=>action=>{
  if(!isFSA(action)){
  return isPromise(action)? action.then(dispatch):next(action);
}

return isPromise(action.payload)
 ? action.payload.then(
    result=>dispatch({...action,payload:result}),
    error=>{
       dispatch({...action,payload:error,error:true});
       return Promise.reject(error);
  }
 )
 : next(action);
 };
}

思绪:redux-promise兼容了FSA规范(相识FSA可参考https://segmentfault.com/a/11…),也就是说将返回的结果保存在payload中。完成历程异常轻易明白,即推断action或action.payload是不是为promise,假如是,就实行then,返回的结果再发送一次dispatch。

此时,action可以写成promise情势(promiseActionCreator):

//应用ES7的async和awaita语法
const fetchData=(url,params)=>fetch(url,params);

async function getWeather(url,params){
  const result=await fetchData(url,params);
  
  if(result.error){
     return{
       type:'GET_WEATHER_ERROR',
       error:'result.error',
       };
    }

    return{
      type:'GET_WEATHER_SUCCESS',
      payload:'result'
    };
}

redux-saga

redux-saga是redux社区一个处置惩罚异步流的后起之秀,它与上述要领最直观的差别就是用generator替代了promise。确实,redux-saga是最文雅的通用处理方案,它有着天真而壮大的协程机制,可以处理任何庞杂的异步交互,细致的,放在另一篇文章中细致引见。

为action定制的自定义异步中间件

在抱负状况下,我们不愿望经由过程庞杂的要领去要求数据,而是愿望经由过程以下情势一并完成在异步要求历程当中的差别状况:

{
  url:'/api/weather.json',
  params:{
     city:encodeURL(city),
   }
 type:['GET_WEATHER','GET_WEATHER_SUCCESS','GET_WEATHER_ERROR'],
}

可以看到,异步要求action的花样有别于FSA。它并没有运用type属性,而运用了types属性。在要求middleware中,会对action举行花样搜检,若存在url和types属性,则申明这个action是一个用于发送异步要求的action。另外,并非一切要求都能照顾参数,因而params是可选的。

const fetchMiddleware=store=>next=>action=>{
  if(!action.url || !Array.isArray(action.types)){
      return next(action);
     }
   const [LOADING,SUCCESS,ERROR]=action.types;
   
   next({
  type: LOADING,
  loading: true,
  ...action,
});

fetch(action.url,{params:action.params})
.then(result=>{
     next({
     type:SUCCES,
     loading:false,
     payload:result,
     });
 })
 .catch(err=>{
      next({
         type:ERROR,
         laoding:false,
         error:err,
         });
 });
}

运用middleware处置惩罚庞杂异步流

在现实场景中,我们不只有短衔接要求,另有轮询要求、多异步串连要求,或是在异步中到场同步处置惩罚的逻辑。这时候我们须要对平常异步中间件举行处置惩罚。

轮询

轮询是长衔接的一种完成体式格局,它可以在肯定时间内重新启动本身,然后再次提议要求。基于这个特征,我们可以在上一个中间件的基础上再写一个middleware,这里命名为redux-polling:

import setRafTimeout,{clearRafTimeout} from 'setRafTimeout';

export default ({dispatch,getState})=>next=>action{
  const {poolingUrl,params,types}=action;
  const isPollingAction=pollingUrl&&params&&types;
  
  if(!isPollingAction){
  return next(action);
}

let timeoutId=null;
const startPolling=(timeout=0)=>{
  timeoutId=setRafTimeout(()=>{
  const pollingAction={
  ...others,
  url:pollingUrl,
  timeoutId,
  };

  dispatch(pollingAction).then(data=>{
      if(data && data.interval && typeof data.interval=='number'){
      startPolling(data.interval*1000);
  }
else
  {
  console.error('pollingAction should fetch data contain interval');
  }
});
    },timeout);
                };
   startPolling();
 }
 
 export const clearPollingTimeout=(timeId)=>
   {
      if(timeoutId){
      clearRafTimeout(timeId);
   }
};

我们用到了raf函数,它可以让要求在肯定时间内重新启动;startPolling函数为递归函数,如许可以,满足轮询的要求;在API的设想上,还暴露了clearPollingTimeout要领,以便我们在须要时手动住手轮询。

末了,挪用action来提议轮询:

{
pollingurl:'/api/weather.json',
params:{
         city:encodeURL(city),
      },
types:[null,'GET_WEATHER-SUCCESS',null],
}

关于长衔接,另有其他多种完成体式格局,最好的体式格局是对其团体做一次封装,在内部完成诸如轮询和WebSocket。

多异步串连

我们可以经由过程promise封装来完成不管是不是是异步要求,都可以经由过程promise来通报以到达一个一致的结果。

const sequenceMiddlware=({dispatch,getState})=>next=>action=>{
     if(!Array.isArray(action)){
          return next(action);
           }

   return action.reduce((result,currAction)=>{
      return result.then(()=>{
        return Array.isArray(currAction)?
              Promise.all(currAction.map(item=>dispatch(item))):
              dispatch(currAction);
   });
  },Promise.resolve());
}

在构建action creator时,会通报一个数组,数组中每个值都是按递次实行的步骤。这里的步骤既可所以异步的,也可所以同步的。在完成历程当中,我们异常奇妙地运用了Promise.resolve()来初始化action.reduce要领,然后运用Promise.then()要领串连起数组,到达了串连步骤的目标。

function getCurrCity(ip){
  return 
  {
  url:'/api/getCurrCity.json',
  param: {ip},
  types: [null,'GET_CITY_SUCCESS',null],
     }
}

return getWeather(cityId){
  return
  {
  url:'/api/getWeatherInfo.json',
  param:{cityId},
  types:[null,'GET_WEATHER_SUUCCESS',null],
   }
}

function loadInitData(ip){
  return
  [
  getCurrCity(ip),
  (dispatch,state)=>{
  dispatch(getWeather(getCityIdWithState(state)));
      },
  ];
}

这类要领应用了数组的特征,它已覆蓋了大部分场景,固然,假如串连历程当中有差别的分支,就无计可施了。

    原文作者:GISChen
    原文地址: https://segmentfault.com/a/1190000014268877
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞