react|redux-thunk和redux-saga
redux-thunk
和redux-saga
都是redux的中间件,都是用来处理异步请求的。中间件是指在action
与store
之间实现某种功能的函数
文章图片
redux-thunk的用法 一般redux中action默认值返回对象,不能返回函数(会报错)。redux-thunk
正好解决了这个问题,它使得action可以返回函数,一般我们就把异步请求写在函数里。
store/index.js
import { createStore, applyMiddleware, compose } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'
const enhancer = composeEnhancers(
applyMiddleware(thunk),
)
const store = createStore(
reducer,
enhancer
)
export default store
组件
TodoList.js
import { getInitDataAction } from './store/actionCreator'
import store from './store'componentDidMount() {
const action = getInitDataAction() // getInitDataAction返回一个函数,返回时会执行这个函数
store.dispatch(action)
}
actionCreator.js
import { INIT_TODO_LIST } from './actionTypes'
import axios from 'axios'export getInitTodoListAction (data) => ({
type: INIT_TODO_LIST,
data
})export getInitDataAction = () => {
return (dispatch) => {
axios.get('/list.json').then(res => {
const data = https://www.it610.com/article/res.data
const action = getIninTodoListAction(data)
dispatch(action)
})
}
}
redux-saga的用法
redux-saga
中间件会把所有异步请求放到一个文件,集中管理,原理是,组件dispatch
某个action
时,会被redux-saga
捕获,再执行相应的函数,函数中执行异步请求。store/index.js
import { createStore, applyMiddleware, compose } from 'redux'
import reducer from './reducer'
import createSagaMiddleware from 'redux-saga'
import mySaga from'./sagas.js'const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const sagaMiddleware = createSagaMiddleware()
const enhancer = composeEnhancers(
applyMiddleware(sagaMiddleware)
)
const store = createStore(
reducer,
enhancer
)
sagaMiddleware.run(mySaga)export default store
sagas.js
import { put, takeEvery } from 'redux-saga/effects'
import { GET_INIT_DATA } from './actionTypes'
import { getInitTodoListAction } from './actionCreator'
import axios from 'axios'function* getInitList() {
try {
const res = yield axios.get('/list.json')
const action = getInitTodoListAction(res.data)
yield put(action)
} catch(e) {
console.log('list.json 连接网络失败')
}
}function* mySaga() {
yield takeEvery(GET_INIT_TADA, getInitList) //当GET_INIT_TODO_LIST的action被dispatch时执行getInitList函数
}export default mySaga
store/actionCreator.js
import { INIT_TODO_LIST, GET_INIT_DATA } from './actionTypes'
import axios from 'axios'export getInitTodoListAction (data) => ({
type: INIT_TODO_LIST,
data
})export getInitDataAction () => ({
type: GET_INIT_DATA
})
【react|redux-thunk和redux-saga】组件
TodoList.js
import { getInitDataAction } from './store/actionTypes'
import store from './store'componentDidMount() {
const action = getInitDataAction()
store.dispatch(action) // redux-saga会捕获到action.type=GET_INIT_DATA的动作,再执行sagas.js中的getInitList函数,执行异步请求
}
推荐阅读
- 急于表达——往往欲速则不达
- 第三节|第三节 快乐和幸福(12)
- 20170612时间和注意力开销记录
- 2.6|2.6 Photoshop操作步骤的撤消和重做 [Ps教程]
- 对称加密和非对称加密的区别
- 眼光要放高远
- 樱花雨
- 前任
- 2020-04-07vue中Axios的封装和API接口的管理
- 烦恼和幸福