### 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)ios
1 // store中index文件 2 import { createStore, applyMiddleware, compose } from 'redux' 3 import creatSagaMiddleware from 'redux-saga' 4 import TodoSagas from './saga' 5 import todoListReducer from './reducer' // 引入圖書列表 6 const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose 7 const sagaMiddleware = creatSagaMiddleware() 8 const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware)) 9 sagaMiddleware.run(TodoSagas) 10 const store = createStore( 11 todoListReducer, 12 enhancer 13 ) 14 15 export default store 16 17 // ------------------------------分割線------------------------------------- 18 19 //在store中 建立sagajs文件 20 import {takeEvery, put} from 'redux-saga/effects' 21 import {GET_INIT_LIST} from './actionTypes' 22 import {initData} from './actionCreators' 23 import axios from 'axios' 24 // es6的generator函數 添加yield會等待異步執行,異步請求執行完以後再執行以後的代碼 25 function* getInitList() { 26 // es6的generator函數 可使用try--catch捕捉異常 27 try{ 28 const res = yield axios.get('http://getTodoList'); 29 const action = initData(res.data.data) 30 yield put(action) 31 }catch(e){ 32 console.log('http://getTodoList 網絡請求失敗') 33 } 34 35 } 36 // sagajs中必定要寫這個函數 37 function* mySaga() { 38 // 捕捉action的類型 39 yield takeEvery(GET_INIT_LIST, getInitList) 40 } 41 export default mySaga