在任何请求和响应之后,调用 api



我需要通过检查一些条件来调用api。但是在任何请求/响应之后都需要此 api 调用。但是我找不到任何有用的东西。

因此,我正在寻找一种使用 redux-saga 设置项目的解决方案,以便我可以在任何请求/响应上调用 api。

例如,我们可以从不同的地方调用不同的 api;

.fetch('/books')
.fetch('/copies')
etc.

现在,我还想在每次获取时调用一个 api(请求之前和响应之后(。希望,这现在已经清楚了。

您是否在 redux-saga: https://github.com/redux-saga/redux-saga/blob/master/docs/advanced/Testing.md#effectmiddlwares 中尝试过 effectmiddlwares ?

假设您有一种可靠的方法来识别作为响应的操作,您可以使用pattern函数来匹配所有响应操作并触发另一个调用。

例如:

// assuming your response success action types all look like "REQUEST_TYPE_SUCCESS"
function isResponse(action) {
return action.type.endsWith("SUCCESS")
}
function* makeApiCall(action) {
// maybe do some logic to determine the api call based on the action
yield call(asyncApiCall, args);
}
function* responseWatcher() {
// consider takeLatest or takeLeading instead of takeEvery depending on your use case
yield takeEvery(isResponse, makeApiCall);
}

然后将responseWatcher添加到您的根传奇中,无论您如何设置它。

如果您需要有关take帮助程序的pattern参数的更多信息,请参阅take的 api 参考:https://redux-saga.js.org/docs/api/#takepattern

最新更新