Redux-saga
基本概念
redux-saga 可以将异步操作从 Action Creator 文件中抽离出来,放在一个单独的文件中。
- redux-saga 下载
npm install redux-saga
- 创建 redux-saga中间件
import createSagaMiddleware from 'redux-saga';
const sagaMiddleware = createSagaMiddleware();
- 注册redux-saga
createStore(reducer, applyMiddleware(sagaMiddleware));
使用saga 接收 action 执行异步操作
- takeEvery 作用是接收action,当组件去触发一个action的时候,在saga文件中用takeEvery 去接收这个action;
- takeEvery第一个参数接收的是那个action的类型字符串;
- takeEvery第二个参数接收的是接收到action后要执行的方法,这是一个Generator函数;
- put 当异步操作返回结果之后,put去触发另一个action把异步操作结果传递给reducer,让reducer把结果保存到store中。 ```javascript import { takeEvery, put } from ‘redux-saga/effects’;
function* load_posts () { const { data } = yield axios.get(‘/api/posts.json’); yield put(load_posts_success(data)); }
export default function* postSaga () { yield takeEvery(LOAD_POSTS, load_posts); }
5.
启动saga
```javascript
import postSaga from './store/sagas/post.saga';
sagaMiddleware.run(postSaga);
action 传参
- 接收参数
// components/Counter.js
const { increment } = props;
...
<button onClick={() => increment_async(20)}>+</button>
- View 传递给 action ```javascript // counter.action.js import { INCREMENT_ASYNC } from “../const/counter.const”;
export const increment_async = payload => ({type: INCREMENT_ASYNC, payload});
3.
saga 接收 action
```javascript
import { takeEvery, put, delay } from 'redux-saga/effects';
import { increment } from '../actions/counter.action';
import { INCREMENT_ASYNC } from '../const/counter.const';
function* increment_async_fn(action) {
yield delay(2000);
yield put(increment(action.payload));
}
export default function* counterSaga() {
// 接收action
// takeEvery第一个参数接收字符串,第二个接收异步函数
yield takeEvery(INCREMENT_ASYNC, increment_async_fn);
}
拆分 Saga
// 新建modal.saga.js
import { takeEvery, put, delay } from 'redux-saga/effects';
import { show } from '../actions/modal.action';
import { SHOWMODAL_ASYNC } from '../const/counter.const';
function* increment_async_fn(action) {
yield delay(2000);
yield put(increment(action.payload));
}
export default function* counterSaga() {
yield takeEvery(SHOWMODAL_ASYNC, showModal_async_fn);
}
合并 saga
- 使用 all 方法合并 saga
- import { all } from ‘redux-saga/effects’;
- all 接收一个 saga 函数的数组;
- 导出的 rootSaga 是一个Generator函数,function*,yield all。
// 新建 saga/root.saga.js
import { all } from 'redux-saga/effects';
import counterSaga from './counter.saga';
import modalSaga from './modal.saga';
export default function* rootSaga() {
yield all([
counterSaga(),
modalSaga()
])
}
// 修改 store/index.js
import rootSaga from './saga/root.saga';
sagaMiddleware.run(rootSaga);