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)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
相关文章
相关标签/搜索