Redux-saga 中间件

2019-10-08  本文已影响0人  参商_70a0

Redux-saga和thunk一样,可以进行异步代码的拆分。
不同的是redux thunk是将异步代码放入action。
而redux saga是将其放入外部的文件中处理。
(1)和thunk一样配置store

import {createStore, applyMiddleware} from "redux"
import reducer from "./reducer"
import createSagaMiddleware from 'redux-saga'
这里就引入了外部的文件
import mySaga from './sagas/sagas'
// import thunk from "_redux-thunk@2.3.0@redux-thunk";
const sagaMiddleware = createSagaMiddleware()

const store=createStore(
   reducer,
   applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(mySaga)
export default store;

(2)编写sagas.js
注:sagas中一定要导出generator函数
当接受到action类型为“GET_SAGA_ACTION”
运行fetchUser方法

import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import {GET_SAGA_ACTION} from '../actionTypes' 
import axios from 'axios'
import {initListAction} from '../actionCreators'
function* mySaga() {
    yield takeEvery(GET_SAGA_ACTION, fetchUser);
}
function* fetchUser(){
    try{
        const res= yield axios.get('https://5ddfa840-ac8e-4521-bb15-135d3d86de70.mock.pstmn.io/api/todoList') 
        const action=initListAction(res.data);
        yield put(action);
    }catch(e){
        console.log("网络请求失败");
    }
}
export default mySaga;

具体流程:
dispatch一个action——》action会被sagas.js接收到
——》如果符合takeEvery里面那个字段,即‘GET_SAGA_ACTION’——》
调用fetchUser方法——》put方法会将新的action传给reducer

上一篇下一篇

猜你喜欢

热点阅读