redux-saga中间件的使用

中间件是值action和store的中间

1、首先安装redux-saga

npm install --save redux-saga

2、在store文件夹下创建saga.js文件
3、在store下的index文件中引入

import createSagaMiddleware from 'redux-saga';
import mySaga from './sagas'
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
);//创建公共仓库
sagaMiddleware.run(mySaga)
export default store;

3、组件中创建action

componentDidMount(){
    const action=getInitList()
    store.dispatch(action)//这个的执行不仅reducer能接收到action,saga也能接收到
}

4、由于saga.js文件可以收到action
首先要对generrator函数熟悉
所以saga中的代码如下

import {  put, takeEvery } from 'redux-saga/effects'
import {GET_INIT_LIST} from './actiontypes'
import axios from 'axios'
import {initList} from './actionCreators'

function* getList() {
    try{
    const res=yield axios.get('/api/todolist');
    const action=initList(res.data);
    yield put(action);
}catch (e) {
    console.log("网络请求失败")
}
}
function* mySaga() {
    yield takeEvery(GET_INIT_LIST, getList);//通过这个捕获到action
}

export default mySaga;

这样就实现了redux-saga中间件的使用

你可能感兴趣的:(前端,react,redux-saga)