redux流程圖.png
redux提供狀態(tài)管理没佑,但不能很好地處理異步操作。這時候需引入中間件
中間件一般是在 View層發(fā)送 Action 的時候,加上一些異步操作巷帝,將action再次加工過以后返回新的action給reducer
中間件.png
image.png
saga是redux中間件的一種匆笤,它將所有的異步操作邏輯集中到一起處理.可以看作是一個后臺進(jìn)程研侣,監(jiān)聽每次被發(fā)起的action,然后調(diào)用相應(yīng)的方法炮捧,即基于這個action來做什么 (比如:是發(fā)起一個異步請求庶诡,還是發(fā)起其他的action到store,還是調(diào)用其他的sagas 等 )有以下特點:
- 異步數(shù)據(jù)獲取的相關(guān)業(yè)務(wù)邏輯放在了單獨的 saga.js 中咆课,不再是摻雜在 action.js 或 component.js 中末誓。
- dispatch 的參數(shù)是標(biāo)準(zhǔn)的 action,沒有魔法书蚪。
- saga 代碼采用類似同步的方式書寫喇澡,代碼變得更易讀。
- 代碼異常/請求失敗 都可以直接通過 try/catch 語法直接捕獲處理殊校。
案例:
store.js
import {createStore,applyMiddleware,compose} from 'redux'
import reducer from './reducer'
// import thunk from 'redux-thunk'
import createSagaMiddleware from 'redux-saga' // 引入redux-saga中的createSagaMiddleware函數(shù)
import mySagas from './sagas'
// 綁定中間件dev-tools
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
// const enhancer = composeEnhancers(applyMiddleware(thunk))
const sagaMiddleware = createSagaMiddleware()
// 中間件晴玖,加載sagaMiddleware
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware))
const store = createStore(reducer,enhancer)
sagaMiddleware.run(mySagas) //執(zhí)行saga里面的函數(shù)
export default store
sagas.js
import {takeEvery,put} from 'redux-saga/effects'
import {GET_MY_LIST} from './actionTypes'
import {getListAction} from './actionCreators'
import axios from 'axios'
//generator
function* mySagas(){
yield takeEvery(GET_MY_LIST,getList) //監(jiān)聽捕獲action,第一個參數(shù)是action type 第二個參數(shù)是調(diào)用函數(shù)
}
function* getList(){
// axios.get('https://www.fastmock.site/mock/dffe9e557e549a34442255ab7356f863/test/api')
// .then((res)=>{
// // const data = res.data.list
// const action=getListAction(res.data.list)
// store.dispatch(action)
// })
// .catch((error)=>{console.log('axios獲取數(shù)據(jù)失敗'+error)})
console.log('xxxxxxxxx')
const res = yield axios.get('https://www.fastmock.site/mock/dffe9e557e549a34442255ab7356f863/test/api')
const action=getListAction(res.data.list)
yield put(action) // 這里將加工后的新的action給reducer
}
export default mySagas
./actionTypes
export const CHANGE_INPUT = 'changeInput'
export const ADD_ITEM = 'addItem'
export const DELETE_ITEM = 'deleteItem'
export const GET_LIST = 'getList'
export const GET_MY_LIST = 'getMyList'
./actionCreators
import {GET_MY_LIST,CHANGE_INPUT,ADD_ITEM,DELETE_ITEM,GET_LIST} from './actionTypes'
export const changeInputAction=(value)=>({type:CHANGE_INPUT,value})
export const clickBtnAction=()=>({type:ADD_ITEM})
export const deleteItemAction=(index)=>({type:DELETE_ITEM,index})
export const getListAction=(data)=>({type:GET_LIST,data})
export const getMylistAction=()=>({
type:GET_MY_LIST
})
TodoList.js
import React, { Component } from 'react';
import TodoListUI from './TodoListUI'
import store from './store'
import {getMylistAction,changeInputAction,clickBtnAction,deleteItemAction} from './store/actionCreators'
// import axios from 'axios'
class TodoList extends Component {
constructor(props) {
super(props);
this.state = store.getState()
this.changeInputValue=this.changeInputValue.bind(this)
this.storeChange=this.storeChange.bind(this)
this.clickBtn=this.clickBtn.bind(this)
this.deleteItem=this.deleteItem.bind(this)
store.subscribe(this.storeChange)
}
render() {
return (
<TodoListUI
inputValue={this.state.inputValue}
changeInputValue={this.changeInputValue}
clickBtn={this.clickBtn}
list={this.state.list}
deleteItem={this.deleteItem}/>); }
componentDidMount(){
const action = getMylistAction()
store.dispatch(action)
}
changeInputValue(e){
const action=changeInputAction(e.target.value)
store.dispatch(action)
}
clickBtn(){
const action=clickBtnAction()
store.dispatch(action)
}
deleteItem(index){
const action=deleteItemAction(index)
store.dispatch(action)
}
storeChange(){
this.setState(store.getState())
}
}
export default TodoList;
從react components組件加載完成,觸發(fā)getMylistAction() 它的類型標(biāo)志是type:GET_MY_LIST呕屎,在saga里監(jiān)聽到GET_MY_LIST被觸發(fā)让簿,則調(diào)用saga里的getList() ,這個方法里去調(diào)用接口秀睛,定義一個新action尔当,前面調(diào)用接口的返回值傳參給reducer去更新state
...略
if (action.type === GET_LIST){
let newState = JSON.parse(JSON.stringify(state))
newState.list=action.data
return newState
}
image.png