Redux 中异步的请求

在 redux 中异步流中间件有很多,当下主流的异步中间件有两种:redux-thunk、redux-saga。

1、redux-thunk

优点:

  •  体积小
  •  使用简单:没有引入像 redux-saga 额外的范式

缺点:

  • 样板代码过度
  • 耦合严重:异步操作与 redux 的 action 耦合在一起,不方便管理
  • 功能孱弱:有些实际开发中的常用狗能需要自己进行封装

使用步骤:

(1)配置中间件,在 store 的创建中配置

import {createStore, applyMiddleware, compose} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk'

// 设置调试工具
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
// 设置中间件
const enhancer = composeEnhancers(
  applyMiddleware(thunk)
);

const store = createStore(reducer, enhancer);

export default store;

(2)添加一个返回函数的 actionCreator,将异步请求逻辑放在里面

/**
  发送get请求,并生成相应action,更新store的函数
  @param url {string} 请求地址
  @param func {function} 真正需要生成的action对应的actionCreator
  @return {function} 
*/
// dispatch为自动接收的store.dispatch函数 
export const getHttpAction = (url, func) => (dispatch) => {
    axios.get(url).then(function(res){
        const action = func(res.data)
        dispatch(action)
    })
}

(3)生成 action,并发送 action

componentDidMount(){
    var action = getHttpAction('/getData', getInitTodoItemAction)
    // 发送函数类型的action时,该action的函数体会自动执行
    store.dispatch(action)
}

2、redux-saga

优点:

  • 异步解耦:异步操作被转移到 saga.js ,不再是掺杂在 action.js 或 component.js 中
  • 异常处理:受益于 generator function 的 saga 实现,代码异常/请求失败 都可以直接通过 try/catch 语法直接捕获处理
  • 功能强大:提供了大量的 saga 辅助函数和 Effect 创建器供开发者使用,开发者无须封装或简单封装即可使用
  • 灵活:可以将多个 sage 可以串行/进行组合起来,形成一个非常实用的异步 flow
  • action 摆脱了 thunk function:dispatch 的参数依然是一个纯粹的 action,而不是充满“黑魔法”的 thunk function
  • 易测试,提供了各种 case 的测试方案,包括mock task,分支覆盖等

缺点:

  • 体积庞大:体积略大,代码近2000行,mini版25kb左右
  • 功能过剩
  • typescript支持不友好:yield 无法返回TS类型

使用步骤:

(1)配置中间件

import {createStore, applyMiddleware, compose} from 'redux';
import reducer from './reducer';
import createSagaMiddleware from 'redux-saga'
import TodoListSaga from './sagas'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const sagaMiddleware = createSagaMiddleware()

const enhancer = composeEnhancers(
  applyMiddleware(sagaMiddleware)
);

const store = createStore(reducer, enhancer);
sagaMiddleware.run(TodoListSaga)

export default store;

(2)将异步请求放在sagas.js中

import {takeEvery, put} from 'redux-saga/effects'
import {initTodoList} from './actionCreator'
import {GET_INIT_ITEM} from './actionTypes'
import axios from 'axios'

function* func(){
    try{
        // 可以获取异步返回数据
        const res = yield axios.get('/getData')
        const action = initTodoList(res.data)
        // 将action发送到reducer
        yield put(action)
    }catch(e){
        console.log('网络请求失败')
    }
}

function* mySaga(){
    // 自动捕获GET_INIT_ITEM类型的action,并执行func
    yield takeEvery(GET_INIT_ITEM, func)
}

export default mySaga

(3)发送action

componentDidMount(){
  const action = getInitTodoItemAction()
  store.dispatch(action)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值