[英]redux and redux-saga UI action triggering multiple API actions
Just trying to understand what the best practice is for a bunch of API calls to depend on a single UI action in redux
and redux-saga
. 只是想了解一堆API调用的最佳实践是什么,它们依赖于
redux
和redux-saga
的单个UI操作。 For instance 例如
SELECTED_ITEM_CHANGE
gets triggered SELECTED_ITEM_CHANGE
被触发 DATA1_REQUEST
, DATA2_REQUEST
, ..., DATA10_REQUEST
DATA1_REQUEST
, DATA2_REQUEST
,..., DATA10_REQUEST
DATA1_REQUEST
, ... , DATA10_REQUEST
get resolved, redux-saga sends a bunch of actions like DATA1_SUCCESS
with data to resolve to the store. DATA1_REQUEST
,..., DATA10_REQUEST
得到解析时,redux-saga将诸如DATA1_SUCCESS
之类的DATA1_SUCCESS
与要解析的数据一起发送到存储中。 I got this part using redux-saga
and I basically understand how to do it. redux-saga
获得了这一部分,我基本上了解了如何做。 My question is, how do I get DATA1_REQUEST
, ... , DATA10_REQUEST
to get triggered when SELECTED_ITEM_CHANGE
gets triggered? 我的问题是,当
SELECTED_ITEM_CHANGE
被触发时,如何获取DATA1_REQUEST
,..., DATA10_REQUEST
来触发? The dumb way is to just do it in the component that sends SELECTED_ITEM_CHANGE
and just dispatch
all of those actions along with the SELECTED_ITEM_CHANGE
action, but this is not modular since the component should not be responsible for all those API calls. 愚蠢的方法是只在发送
SELECTED_ITEM_CHANGE
的组件中执行此操作,然后dispatch
所有这些动作与SELECTED_ITEM_CHANGE
动作一起dispatch
,但这不是模块化的,因为该组件不应对所有这些API调用负责。 So who should handle this? 那么谁来处理呢? I guess there's a couple options:
我猜有两种选择:
SELECTED_ITEM_CHANGE
also dispatch DATA1_REQUEST
, ..., DATA10_REQUEST
. SELECTED_ITEM_CHANGE
的动作创建者也调度DATA1_REQUEST
,..., DATA10_REQUEST
。 SELECTED_ITEM_CHANGE
and dispatch DATA1_REQUEST
, ..., DATA10_REQUEST
SELECTED_ITEM_CHANGE
并调度DATA1_REQUEST
,..., DATA10_REQUEST
I'm leaning towards the second, but I'm not very sure. 我倾向于第二个,但是我不太确定。
Thanks for your help! 谢谢你的帮助!
Option 2 is your option, that's the whole point behind redux-saga
AFAIK. 选项2是您的选择,这是
redux-saga
AFAIK的全部要点。 You can simply use takeEvery
(would allow multiple requests) or takeLatest
to listen for SELECTED_ITEM_CHANGE
action and yield to another saga that actually performs the network requests. 您可以简单地使用
takeEvery
(将允许多个请求)或takeLatest
来侦听SELECTED_ITEM_CHANGE
动作,并屈服于实际执行网络请求的另一个传奇。
You can see an example right in the documentation here: https://redux-saga.js.org/docs/basics/UsingSagaHelpers.html 您可以在这里的文档中看到一个示例: https : //redux-saga.js.org/docs/basics/UsingSagaHelpers.html
Excerpt: 摘抄:
import { takeLatest } from 'redux-saga/effects'
function* fetchData(){
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 takeLatest('FETCH_REQUESTED', fetchData)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.