Redux-Saga
直感的な Redux の副作用管理者。
管理が簡単で、テストが簡単で、効率的に実行されます。
非同期
ES6 ジェネレーターにより、非同期フローを読みやすく、書きやすく、テストしやすくなりました。詳細にこだわらずに複雑な副作用を作成します。
構成重視
Saga では、並列実行、タスクの同時実行、タスクの競合、タスクのキャンセルなどへの対処方法を数多く利用できます。コードのフローを完全に制御します。
テストが簡単
ジェネレーターの各ステップまたは佐賀全体の結果をアサートします。どちらの方法でも、サイドエフェクトのテストは迅速で簡潔かつ簡単で、テストがそのはずであるためです。
例の使用
- 1. アクションのディスパッチ
- 2. 副作用を開始する
- 3. ストアに接続する
- 4. ストアに接続する (新バージョン)
ボタンがクリックされたときにリモートサーバーから一部のユーザーデータをフェッチするための UI があると仮定します。(簡潔にするため、アクショントリガーコードのみを表示します。)
class UserComponent extends React.Component {...onSomeButtonClicked() {const { userId, dispatch } = this.propsdispatch({type: 'USER_FETCH_REQUESTED', payload: {userId}})}...}
コンポーネントは、プレーンオブジェクトアクションをストアにディスパッチします。すべての watch を作成します USER_FETCH_REQUESTED
アクションを実行して、ユーザーデータをフェッチするための API 呼び出しをトリガーします。
import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'import Api from '...'// Worker saga will be fired on USER_FETCH_REQUESTED actionsfunction* fetchUser(action) {try {const user = yield call(Api.fetchUser, action.payload.userId);yield put({type: "USER_FETCH_SUCCEEDED", user: user});} catch (e) {yield put({type: "USER_FETCH_FAILED", message: e.message});}}// Starts fetchUser on each dispatched USER_FETCH_REQUESTED action// Allows concurrent fetches of userfunction* mySaga() {yield takeEvery("USER_FETCH_REQUESTED", fetchUser);}
Saga を実行するには、redux-saga
ミドルウェアを使用して Redux ストアに接続する必要があります。
import { createStore, applyMiddleware } from 'redux'import createSagaMiddleware from 'redux-saga'import reducer from './reducers'import mySaga from './sagas'// Create the saga middlewareconst sagaMiddleware = createSagaMiddleware()// Mount it on the Storeconst store = createStore(reducer,applyMiddleware(sagaMiddleware))// Then run the sagasagaMiddleware.run(mySaga)// Render the application
これは Redux
から createStore
ではなく reduxjs/toolkit
から configureStore
を使用して佐賀を実行する新しいバージョンです。
import { configureStore } from '@reduxjs/toolkit'import createSagaMiddleware from 'redux-saga'import reducer from './reducers'import mySaga from './sagas'// Create the saga middlewareconst sagaMiddleware = createSagaMiddleware()const middleware = [sagaMiddleware]// Mount it on the Storeconst store = configureStore({reducer,middleware: (getDefaultMiddleware) =>getDefaultMiddleware().concat(middleware),})// Then run the sagasagaMiddleware.run(mySaga)// Render the application