到https://github.com搜索redux-saga,点击### redux-saga / redux-saga
这里会详细的告诉我们redux-saga.
一.redux-saga的配置
1.安装
npm install --save redux-saga
or
yarn add redux-saga
2.引入
在store的index.js文件中引入createSagaMiddleware(帮助我们创建中间件的方法)
import createSagaMiddleware from 'redux-saga'
3.创建中间件
通过这个方法生成一个sagaMiddleware
const sagaMiddleware = createSagaMiddleware();
用composeEnhancers将sagaMiddleware这个中间件传入进去
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware));
4.创建sagas.js文件
在store的index.js中引入sagas
import todoSagas from './sagas';
创建好store之后调用sagaMiddleware.run方法
sagaMiddleware.run(todoSagas)
这时运行是会报错的,需要去saga.js中添加代码
function* todoSagas() {
}
export default todoSagas;
运行网页,不报错的话redux_saga就配置成功了。
二.redux-saga实现异步操作
1.到actionCreators.js中创建一个方法返回的action是对象
export const getInitList = () => ({
type:GET_INIT_LIST,
})
2.当组件加载完成之后的方法,调用actionCreator去创建一个action
componentDidMount() {
const action = getInitList();
store.dispatch(action);
//有了redux-saga之后,除了reducer可以接收action,sagas也可以接收
}
3.sagas.js接收action
import {takeEvery} from 'redux-saga/effects';
//使用takeEvery方法
//这里要求必须使用generator函数,可以先使用,以后再了解
function* todoSaga() {
//takeEvery 就是去捕捉每一个类型
yield takeEvery(GET_INIT_LIST, getInitList);
//只要我接收了一个GET_INIT_LIST类型的action的话,我就会指向getInitList这个方法
}
getInitList方法
function * getInitList() {
console.log('abc');
}
打印成功,我们就可以在getInitList方法里进行异步请求了
import {takeEvery, put} from 'redux-saga/effects';
import {initListAction} from './actionCreators';
import axios from 'axios';
function * getInitList() {
axios.get('/List.json').then((res) => {
const data = res.data;
const action = initListAction(data);
console.log(action);
})
}
上面代码块儿写法是错误,这里用了generator函数,generator函数里面做异步请求的时候就不要用promise这种形式了
function * getInitList() {
try {
const res = yield axios.get('/list.json'); //等待axios获取完毕,将结果直接存在res里
const action = initListAction(res.data);
yield put(action);//等action处理完成之后,再往下执行代码
}catch (e) {
console.log('list.json网络请求失败');
}
}