Sagas
Sagas
我们可以理解为


基础使用
在定义生成
// npm install --save redux-saga
import { createStore, applyMiddleware } from "redux";
import createSagaMiddleware from "redux-saga";
import reducer from "./reducers";
import mySaga from "./sagas";
// create the saga middleware
const sagaMiddleware = createSagaMiddleware();
// mount it on the Store
const store = createStore(reducer, applyMiddleware(sagaMiddleware));
// then run the saga
sagaMiddleware.run(mySaga);
副作用
副作用,顾名思义,在主要作用(
-
takeEvery 类似于redux-thunk 的作用,会在接到相应的action 之后不断产生新的副作用。比如,做一个计数器按钮,用户需要不断的点击按钮,对后台数据更新,这里可以使用takeEvery 来触发。 -
takeLatest 在相同的action 被触发多次的时候,之前的副作用如果没有执行完,会被取消掉,只有最后一次action 触发的副作用可以执行完。比如,我们需要一个刷新按钮,让用户可以手动的从后台刷新数据,当用户不停单机刷新的时候,应该最新一次的请求数据被刷新在页面上,这里可以使用takeLatest 。
在下面的事例中,当我们点击FETCH_REQUESTED
动作,然后
import { call, put } from "redux-saga/effects";
import { takeEvery } from "redux-saga";
export function* fetchData(action) {
try {
const data = yield call(Api.fetchUser, action.payload.url);
yield put({ type: "FETCH_SUCCEEDED", data });
} catch (error) {
yield put({ type: "FETCH_FAILED", error });
}
}
function* watchFetchData() {
yield* takeEvery("FETCH_REQUESTED", fetchData);
}
注意,
import { takeLatest } from "redux-saga/effects";
function* watchFetchData() {
yield takeLatest("FETCH_REQUESTED", fetchData);
}
import { takeEvery } from 'redux-saga/effects'
// FETCH_USERS
function* fetchUsers(action) { ... }
// CREATE_USER
function* createUser(action) { ... }
// use them in parallel
export default function* rootSaga() {
yield takeEvery('FETCH_USERS', fetchUsers)
yield takeEvery('CREATE_USER', createUser)
}