上一篇文章介紹了redux-thunk中間件,redux-thunk中間件主要使action返回函數(shù)成為了可能,可以把異步請求放在action中,今天給大家介紹另一種中間件憾股,redux-saga,可以將異步請求統(tǒng)一放在sagas.js中
參考文檔:GitHub https://github.com/redux-saga/redux-saga
第一步驟:安裝中間件
npm install --save redux-saga //yarn add redux-saga也是可以的
根據(jù)官網(wǎng)提供的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 = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware));
const store = createStore(
reducer,
enhancer
);
sagaMiddleware.run(todoSagas)
export default store;
此時此刻我們發(fā)現(xiàn)store.js中多了一句話:sagaMiddleware.run(todoSagas)箕慧,todoSagas是從sagas中引過來的服球,具體思路是什么呢?
就是我們需要建立一個sagas.js文件颠焦,可以專門來存放異步請求斩熊,然后在store.js中需要調用saga中間件的run的方法去運行起來
好的,下面開始走下面的流程
第二步驟:在同一管理action的地方定義新的action變量
actionCreator.js
//getInitList函數(shù)返回一個對象伐庭,對象中有一個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能夠監(jiān)聽到action,而sagas.js同樣也能監(jiān)聽到狀態(tài)
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('網(wǎng)絡請求失敗')
}
}
// generator 函數(shù)
function* mySaga() {
yield takeEvery(GET_INIT_LIST, getInitList);
}
export default mySaga;
其中takeEvery是redux-saga的方法渣叛,目的是監(jiān)聽到action丈秩,而put的作用相當于dispatch的作用盯捌,將action傳給store