redux-saga中间件

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文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值