Redux進階三:使用redux-saga使用入門

上一篇文章介紹了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 = 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;

此時此刻我們發現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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章