react入门系列之redux-saga中间件

redux-saga中间件

  • 也是一个做异步拆分的中间件
  • 安装 yarn add redux-saga
  • import creatSagaMiddleware from 'redux-saga'
  • import TodoSagas from './saga'
  • const sagaMiddleware = creatSagaMiddleware()
  • const enhancer = composeEnhancers(applyMiddleware(creatSagaMiddleware))
  • sagaMiddleware.run(TodoSagas)
// store中index文件
import { createStore, applyMiddleware, compose } from 'redux'
import creatSagaMiddleware from 'redux-saga'
import TodoSagas from './saga'
import todoListReducer from './reducer' // 引入图书列表
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose
const sagaMiddleware = creatSagaMiddleware()
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware))
sagaMiddleware.run(TodoSagas)
const store = createStore(
    todoListReducer,
    enhancer
)

export default store
//在store中 创建sagajs文件
import {takeEvery, put} from 'redux-saga/effects'
import {GET_INIT_LIST} from './actionTypes'
import {initData} from './actionCreators'
import axios from 'axios'
// es6的generator函数 添加yield会等待异步执行,异步请求执行完之后再执行之后的代码
function* getInitList() {
    // es6的generator函数 可以使用try--catch捕捉异常
    try{
        const res = yield axios.get('http://getTodoList');
        const action = initData(res.data.data)
        yield put(action)
    }catch(e){
        console.log('http://getTodoList 网络请求失败')
    }

}
// sagajs中一定要写这个函数
function* mySaga() {
    // 捕捉action的类型
    yield takeEvery(GET_INIT_LIST, getInitList)
}
export default mySaga
posted @ 2019-09-06 16:06  Byhua  阅读(374)  评论(0编辑  收藏  举报