上一篇文章介绍了 redux-thunk 中间件, redux-thunk 中间件主要使 action 返回函数成为了可能, 可以把异步请求放在 action 中, 今天给大家介绍另一种中间件, redux-saga, 可以将异步请求统一放在 sagas.JS 中
参考文档: GitHub https://github.com/redux-saga/redux-saga
第一步骤: 安装中间件
NPM install --save redux-saga //yarn add redux-saga 也是可以的
根据官网提供的 main.JS 去改变项目中 store.JS 文件
store.JS
- import {createStore, applyMiddleware, compose} from 'redux';
- // import thunk from 'redux-thunk';
- import createSagaMiddleware from 'redux-saga';
- import todoSagas from './sagas'
- import reducer from './reducer';
- const sagaMiddleware = createSagaMiddleware()
- const composeEnhancers = Windows.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? Windows.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
- const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware));
- const store = createStore(
- reducer,
- enhancer
- );
- sagaMiddleware.run(todoSagas)
- export default store;
此时此刻我们发现 store.JS 中多了一句话: sagaMiddleware.run(todoSagas),todoSagas 是从 sagas 中引过来的, 具体思路是什么呢?
就是我们需要建立一个 sagas.JS 文件, 可以专门来存放异步请求, 然后在 store.JS 中需要调用 saga 中间件的 run 的方法去运行起来
好的, 下面开始走下面的流程
第二步骤: 在同一管理 action 的地方定义新的 action 变量
actionCreator.JS
- //getInitList 函数返回一个对象, 对象中有一个 type 类型
- export const getInitList = () => ({
- type : GET_INIT_LIST
- })
第三步骤: 在需要请求的地方建立 action, 同时通过 dispatch 传递给 store
demo.JS
- componentDidMount(){
- const action = getInitList()
- console.log(action)
- store.dispatch(action)
- }
第四步骤: 此时此刻, sagas.JS 开始起作用了, 相当于除了 reducer.JS 能够监听到 action, 而 sagas.JS 同样也能监听到状态
sagas.JS
- import { takeEvery,put } from 'redux-saga/effects'
- import { GET_INIT_LIST } from './actionTypes'
- import {initListAction} from './actionCreators'
- import axios from 'axios'
- function* getInitList(){
- try{
- const res = yield axios.get("https://www.easy-mock.com/mock/5c4173448ff5e33c8a22766e/example/listdata")
- const action = initListAction(res.data.result)
- yield put(action)
- }catch(e){
- console.log('网络请求失败')
- }
- }
- // generator 函数
- function* mySaga() {
- yield takeEvery(GET_INIT_LIST, getInitList);
- }
- export default mySaga;
其中 takeEvery 是 redux-saga 的方法, 目的是监听到 action, 而 put 的作用相当于 dispatch 的作用, 将 action 传给 store
来源: http://www.jianshu.com/p/2002aca15a46