redux流程图.png
redux提供状态管理,但不能很好地处理异步操作。这时候需引入中间件
中间件一般是在 View层发送 Action 的时候,加上一些异步操作,将action再次加工过以后返回新的action给reducer
中间件.png
image.png
saga是redux中间件的一种,它将所有的异步操作逻辑集中到一起处理.可以看作是一个后台进程,监听每次被发起的action,然后调用相应的方法,即基于这个action来做什么 (比如:是发起一个异步请求,还是发起其他的action到store,还是调用其他的sagas 等 )有以下特点:
- 异步数据获取的相关业务逻辑放在了单独的 saga.js 中,不再是掺杂在 action.js 或 component.js 中。
- dispatch 的参数是标准的 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函数
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) //执行saga里面的函数
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) //监听捕获action,第一个参数是action type 第二个参数是调用函数
}
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获取数据失败'+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组件加载完成,触发getMylistAction() 它的类型标志是type:GET_MY_LIST,在saga里监听到GET_MY_LIST被触发,则调用saga里的getList() ,这个方法里去调用接口,定义一个新action,前面调用接口的返回值传参给reducer去更新state
...略
if (action.type === GET_LIST){
let newState = JSON.parse(JSON.stringify(state))
newState.list=action.data
return newState
}
image.png