美文网首页
Redux-saga使用

Redux-saga使用

作者: zhCN_超 | 来源:发表于2017-07-16 11:13 被阅读1565次

    2017/06/24
    新单位全新的前端工程,使用到了redux-saga,学习了很久,整理个大概思路。

    大致思路

    action

    改变storeaction,需要定义reducer,并使用combineReducers返回给createStore
    而请求后台数据的action,需要定义saga函数,下文提及。

    reducer和saga函数

    改变store的那些action,我们仍然需要写switch语句的reducer
    saga函数里面则可以使用它的Generator函数进行优雅的多个异步并行、串行操作。

    import {all,takeEvery} from 'redux-saga/effects';
    import {SAGA_ACTION_TYPE} from './actions'; // 请求后台数据的 action
    
    function* doMoreThings(){
      // 这里调用下文提及的 异步调用
      // 使用 yield 语句(可阻塞、非阻塞)
      // 可以发起其它 action 的 dispatch,不管是改变 store 的 action 还是 异步请求 action
      // 使用到的 effects:put, call, select, fork 等
    }
    
    function* watch(){
      // 由 saga 来监听这个 action 的 dispatch
      // 一旦在程序中任何地方被 dispatch,则调用第二个参数的 Generator 函数
      yield* takeEvery(SAGA_ACTION_TYPE, doMoreThings);
      // more takeEvery
    }
    
    // 返回 saga,供 redux 的中间件使用
    export default function* saga(){
      yield.all([
        watch()
      ])
    }
    
    

    异步处理

    工程使用fetch这个新API来请求后台接口数据,不考虑IE浏览器,它可以替代ajaxXMLHttpRequest
    fetch基于Promise设计,他让我们可以优雅的编写异步调用,告别callback hell
    模块化思路:

    1. 写一个通用的fetch处理函数,只接受两个参数:请求地址url和请求参数options
    2. 写特定的fetch函数,函数内调用上部的函数

    连接 redux

    import { createStore, applyMiddleware } from 'redux';
    import createSagaMiddleware from 'redux-saga';
    
    const sagaMiddleware = createSagaMiddleware();
    
    import yourRootReducers from './rootReducers';
    import yourRootSagas from './rootSagas';
    
    const store = createStore(
      yourRootReducers,
      applyMiddleware(createSagaMiddleware(sagaMiddleware))
    );
    sagaMiddleware.run(yourRootSagas);
    

    相关文章

      网友评论

          本文标题:Redux-saga使用

          本文链接:https://www.haomeiwen.com/subject/abetkxtx.html