react-saga

​ 首先中间件有很多,你可以把他当作一个函数,或者是说是一个模块,
想必你用过 react-thunk ,react-logger…,那么thunk也可以完成saga的工作,只能说有的人喜欢挑战,就是要用saga
主要是想让saga来处理异步请求操作

saga

saga自述

  1. 安装saga yarn add react-saga

  2. 在你的redux主仓库中添加,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // 2. 引入saga 引入saga的主要处理文件
    import createSagaMiddleware from 'redux-saga';
    // @是配了别名的,写的路径就是你saga文件的路径
    import todoSaga from '@/views/TodoList/store/todoSaga';
    // 3.创建saga中间件
    const sagaMiddleware = createSagaMiddleware();
    .
    .
    .
    // 仓库暴露出去的东西
    export default createStore(
    combineReducers({
    todo: todoReducer
    }),
    composeEnhancers(
    // 使用上中间件
    applyMiddleware(sagaMiddleware))

    );
    // run todoSaga
    sagaMiddleware.run(todoSaga)
  3. 在仓库中(我这边是组件的小仓库)创建saga文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    // 注意这个,这里是saga提供的一些方法
    import { takeEvery, put } from 'redux-saga/effects';

    import { FETCH_TODO_LIST } from './actionTypes';
    import { initTodoListAction } from './actionCreates';

    // 处理一个异步请求
    function* init () {
    let response = yield fetch('http://localhost:3001/todoList');
    let res = yield response.json();
    yield put (initTodoListAction(res));
    }

    // 暴露一个方法
    const todoSaga = function *() {
    // takeEvery('action type',要做的事情)
    // 监听/拦截到这个动作,进行操作
    yield takeEvery(FETCH_TODO_LIST, init);
    }
    export default todoSaga;
    /**
    *这边的saga作为中间件利用takeEvery拦截到组件(ui组件发出的action),
    *对action.type做拦截,然后在这个文件里,做异步请求。在请求完成后再将数据通过
    *saga提供的方法put===store.dispatch
    *派发了以后,会进入到reducer中,对仓库里的数据进行一些操作
    */

熟能生巧!

Share
3 min. read