redux-saga
import {
takeEvery,
takeLatest,
throttle,
put,
take,
call,
all
} from 'redux-saga/effects' // 1-引包
//takeEvery(监听参数,回调)----->短时间内触发多次接口,执行多次接口
//takeLatest(监听参数,回调)---->短时间内触发多次接口,只会执行最后一次,中间的会被后面的覆盖
//throttle(时间,监听参数,回调)-->短时间内触发多次接口,会执行第一次和最近的一次(即 第二次),节流阀效果
//put----> 等接口回来以后,发送dispatch
//take--->阻塞代码执行的
while (true) {
yield take('take')//阻塞代码执行
console.log('take>>>>');
}
//all--->多模块执行
//call-->调用接口的
call(axios.get,地址名,携带的参数)
import(takeEvery,put,select , call) from 'redux-saga'
import Asiox from 'axios'
export function* defLogin(){
yield takeEvery('login',function*(){//takeEvery,点击几次触发几次不会
try{
const data = yield select(state=>state.user.data)//从reducer中获取数据
const res = yield call(
Axios.get,
'http://...请求路径',
{params:data}//请求参数
)
yield put(
type:'success',
//传入想传的
)
}catch(e){
//接口错误
yield put({
type:'error'
})
}
})
yield takeLatest('...(监听dispatch的type)',function*(){
try{}catch(e){}
})
.......
yield throttle(1000(时间),'....(监听dispatch的type)',function*(){
try{}catch(e){}
})
...
}
import{all} from 'redux-saga'
import {defLogin} from './login'
export function*(){
yield all([defLogin(),...])//适用于多模块
}
import { combineReducers } from 'redux'
function defReducer(state = [], action) {
switch (action.type) {
case 'login':
return Object.assign({}, state, action)
//对于需要异步操作的,把所有的信息包裹成对象返回给saga
case 'success':
return {
status:1
//返回给页面,将会在prop中 ,
/*
页面中
在页面中利用componentwillUpdate(newvalue) 或者componentDidUpdate(oldvalue)
根据新/旧props与this.props进行比较判断props有没有更新
componentWillUpdate(newProps){
if(newProps!==this.props){
const{status} = this.props
......根据status进行其他操作,跳页面等等。。。
}
}
*/
}
case 'error':
return {
status:0
}
default:
return state
}
}
export default combineReducers({//将多个reducer导出
defReducer,
aaa,
...
})
import { createStore, applyMiddleware } from 'redux'
import { defSage } from './sage' //1---将所有的saga引入
import reducer from './reducer' //2--引入reducer
import createdMiddleware from 'redux-saga'
const sagaMiddleware = createdMiddleware()
export default createStore(
defReducer,
{},
applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(defSage)
//以下代码带有调试工具
import { createStore, applyMiddleware } from 'redux'
import createdApplyMiddleware from 'redux-saga'
import { defSaga } from './saga'
import reducer from './reducer'
import { compose } from 'redux'
const sagaMiddleware = createdApplyMiddleware()
const composeEnhancers =
typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
: compose
const enhancder = composeEnhancers(applyMiddleware(sagaMiddleware))
export default createStore(reducer, enhancder)
sagaMiddleware.run(defSaga)