
时间紧迫?先克隆 GitHub 仓库代码吧!
git clone --branch redux-saga https://github.com/rajjeet/react-quick-start redux-saga-quick-start
cd redux-saga-quick-start
npm install
npm startredux-saganpm install redux-saga/src/configure-store.js
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import "regenerator-runtime/runtime";
...applyMiddleware 是一个辅助函数,为 redux 的 dispatch 函数添加了功能。
默认的 redux-saga 导出(在代码中为 createSagaMiddleware)是创建中间件实例的工厂。
通过导入 regenerator-runtime/runtime 允许 Babel 进行异步动作的转译,而不会出现任何问题。如果忽略此行,则你的应用会失败,并显示以下错误消息:Uncaught ReferenceError:regeneratorRuntime is not defined。
/src/configure-store.js
function* exampleSaga() {
console.log("Example saga reached");
}Saga 只是生成器函数。与正常函数不同,生成器可以用 yield 关键字暂停对异步语句的执行。
与根 reducer( createStore 的第一个参数)一样,此 saga 充当一棵树的根,其中每个树节点都将是另一个 saga。这使我们可以将 saga 和 reducers 并置在使用它们的组件附近。这也使它们易于管理,因为它们仅包含与附近文件相关的代码。
在例子中,exampleSaga只是执行一次并终止的普通函数。我们将在以后的教程中探讨生成器的用法。
/src/configure-store.js
const sagaMiddleware = createSagaMiddleware();执行我们代码中的 redux-saga 默认导入来获取 saga 中间件的实例。
/src/configure-store.js
export const store = createStore(countReducer, applyMiddleware(sagaMiddleware));applyMiddleware(sagaMiddleware) 返回 store enhancer。通过使用工具函数 applyMiddleware,我们可以组合多个中间件并返回一个 store enhancer。 createStore 仅接受单个 store enhancer,因此需要 applyMiddleware。我们将为多个中间件使用一个中间件数组。
/src/configure-store.js
sagaMiddleware.run(exampleSaga);run() 用来接受生成器并在后台运行该进程。通过该过程,我们可以并行创建多个过程并执行许多与 Redux 相关的函数。另外要注意,它必须在应用 saga 中间件之后运行。
这是整合 redux-saga 之后我们最终 store 的配置。
/src/configure-store.js
import { createStore, applyMiddleware } from 'redux';
import { countReducer } from './counter/reducer';
import createSagaMiddleware from 'redux-saga';
import "regenerator-runtime/runtime";
function* exampleSaga() {
console.log("Example saga reached");
}
const sagaMiddleware = createSagaMiddleware();
export const store = createStore(countReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(exampleSaga);这就是在程序中使用 redux-saga 的最低要求, 非常简单。