入門
安裝
$ npm install redux-saga
或
$ yarn add redux-saga
或者,您也可以直接於 HTML 網頁的 <script>
標籤中使用提供的 UMD 組建。參閱 此區塊。
使用範例
假設我們有一個 UI,可以在按鈕被點擊時從遠端伺服器提取一些使用者資料。(為了簡潔起見,我們只會顯示動作觸發程式碼)
class UserComponent extends React.Component {
...
onSomeButtonClicked() {
const { userId, dispatch } = this.props
dispatch({type: 'USER_FETCH_REQUESTED', payload: {userId}})
}
...
}
組件會將一個純物件動作發送到商店。我們將建立一個 Saga,用於監控所有 USER_FETCH_REQUESTED
動作,並觸發一個 API 呼叫來提取使用者資料。
sagas.js
import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...'
// worker Saga: will be fired on USER_FETCH_REQUESTED actions
function* 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 user.
*/
function* mySaga() {
yield takeEvery('USER_FETCH_REQUESTED', fetchUser)
}
/*
Alternatively you may use takeLatest.
Does not allow concurrent fetches of user. If "USER_FETCH_REQUESTED" gets
dispatched while a fetch is already pending, that pending fetch is cancelled
and only the latest one will be run.
*/
function* mySaga() {
yield takeLatest('USER_FETCH_REQUESTED', fetchUser)
}
export default mySaga
要執行我們的 Saga,我們必須使用 redux-saga
中介軟體將其連接到 Redux 商店。
main.js
import { configureStore } from '@reduxjs/toolkit'
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 = configureStore({
reducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(sagaMiddleware),
})
// then run the saga
sagaMiddleware.run(mySaga)
// render the application
在瀏覽器中使用 UMD 建置
dist/
資料夾中也提供 redux-saga
的UMD 建置。使用 umd 建置時,redux-saga
會在 window 物件中以 ReduxSaga
的形式提供。您就能依照這個方式,不需要使用 ES6 import
語法即可建立 Saga 中介軟體
var sagaMiddleware = ReduxSaga.default()
如果您不使用 Webpack 或 Browserify,UMD 版本會很有用。您可以直接從 unpkg 存取它。
以下提供可用的建置
- https://unpkg.com/redux-saga/dist/redux-saga.umd.js
- https://unpkg.com/redux-saga/dist/redux-saga.umd.min.js
重要!如果您鎖定的瀏覽器不支援ES2015 產生器,您必須將它們轉譯(例如,使用 babel 外掛),並提供有效的執行時期,例如 此處。執行時期必須在redux-saga之前匯入
import 'regenerator-runtime/runtime'
// then
import sagaMiddleware from 'redux-saga'