redux-saga需要定义generator函数
-
store.js
import {applyMiddleware,createStore,compose} from ‘redux’
import reducers from ‘./reducers.js’
import creactSagaMiddleware from ‘redux-saga’
import mySagas from ‘./sagas’//导入generator函数
//配置redux-saga与redux-devtools一起使用,compose为绑定两者的方法
const composeEnhancers=window.REDUX_DEVTOOLS_EXTENSION_COMPOSE?
window.REDUX_DEVTOOLS_EXTENSION_COMPOSE({}) : compose
const sagaMiddleware=creactSagaMiddleware()
const enhancer=composeEnhancers(applyMiddleware(sagaMiddleware))
const store =createStore(reducers,enhancer)
//调用执行mySagas文件中的generator
sagaMiddleware.run(mySagas)
export default store -
sagas.js
import {takeEvery,put} from 'redux-saga/effects' //takeEvery为绑定监听的事件,put取代dispatch
import {GET_MYLIST} from './action-types'
import {getListAction} from './actions' //getListAction在function* getList间接使用
import axios from 'axios'
// saga中间件
function* mySagas(){
yield takeEvery(GET_MYLIST,getList)
}
function* getList(){
const res=yield axios.get('https://douban.uieee.com/v2/book/search?q=虚构类&count=8')
console.log(res.data.books)
const action=getListAction(res.data.books)
//分发到reducers
yield put(action)
}
export default mySagas
action.js
export const getMyList=()=>({
type:GET_MYLIST //此处在saga中被监听
})
export const getListAction=(data)=>({type:GET_TODO_LIST,data:data})
//saga中间件调用getListAction并put(action)到reducer的action.type=GET_TODO_LIST
app.js
getToDoList=()=>{
const action=getMyList()
store.dispatch(action) //此调用方法触发saga函数调用
}
reducer.js
根据saga在function* getList(){}数据更新,详情查看saga文件