跳至主要內容

名詞解釋

這是 Redux Saga 核心條款的詞彙。

效應

效應是一個明確的 JavaScript 物件,其中包含一些由 saga 中間軟體執行的指令。

使用 redux-saga 函式庫提供的工廠函式建立效應。例如,使用 call(myfunc, 'arg1', 'arg2') 指示中間軟體呼叫 myfunc('arg1', 'arg2') 並將結果傳回至產生效應的 Generator。

任務

任務就像在後台執行的程序。在基於 redux-saga 的應用程式中,可以有多個任務並行執行。使用 fork 函式建立工作。

import {fork} from "redux-saga/effects"

function* saga() {
...
const task = yield fork(otherSaga, ...args)
...
}

封鎖/非封鎖呼叫

封鎖呼叫表示 Saga 產生了一個效應,並且會等到執行結果後才會恢復至產生效應的 Generator 中下一條指令。

非封鎖呼叫表示 Saga 在產生效應後將立即繼續執行。

例如

import {call, cancel, join, take, put} from "redux-saga/effects"

function* saga() {
yield take(ACTION) // Blocking: will wait for the action
yield call(ApiFn, ...args) // Blocking: will wait for ApiFn (If ApiFn returns a Promise)
yield call(otherSaga, ...args) // Blocking: will wait for otherSaga to terminate

yield put(...) // Non-Blocking: will dispatch within internal scheduler

const task = yield fork(otherSaga, ...args) // Non-blocking: will not wait for otherSaga
yield cancel(task) // Non-blocking: will resume immediately
// or
yield join(task) // Blocking: will wait for the task to terminate
}

守護程式/工作程序

是指使用兩個單獨的 Sagas 組織控制流程的一種方式

  • 守護程式:將觀察已傳送的動作並在每個動作上派生工作程序

  • 工作程序:將處理動作並終止

範例

function* watcher() {
while (true) {
const action = yield take(ACTION)
yield fork(worker, action.payload)
}
}

function* worker(payload) {
// ... do some stuff
}