gpt4 book ai didi

javascript - 如何使用 Redux-Saga 避免重复的 API 请求?

转载 作者:数据小太阳 更新时间:2023-10-29 05:07:20 25 4
gpt4 key购买 nike

到目前为止,与其他 Flux 实现相比,我更喜欢 Redux,并且我正在使用它来重写我们的前端应用程序。

我面临的主要困难点:

  1. 维护 API 调用的状态以避免发送重复请求。
  2. 维护记录之间的关系。

第一个问题可以通过在每种数据类型的子状态中保留一个状态字段来解决。例如:

function postsReducer(state, action) {
switch(action.type) {
case "FETCH_POSTS":
return {
...state,
status: "loading",
};
case "LOADED_POSTS":
return {
status: "complete",
posts: action.posts,
};
}
}

function commentsReducer(state, action) {
const { type, postId } = action;
switch(type) {
case "FETCH_COMMENTS_OF_POST":
return {
...state,
status: { ...state.status, [postId]: "loading" },
};
case "LOADED_COMMENTS_OF_POST":
return {
status: { ...state.status, [postId]: "complete" },
posts: { ...state.posts, [postId]: action.posts },
};
}
}

现在我可以为帖子制作一个传奇,为评论制作另一个传奇。每个 Sagas 都知道如何获取请求的状态。但这会很快导致大量重复代码(例如帖子、评论、点赞、 react 、作者等)。

我想知道是否有避免所有重复代码的好方法。

当我需要通过 ID 从 redux 商店获取评论时,第二个问题就出现了。是否有处理数据之间关系的最佳做法?

谢谢!

最佳答案

redux-saga now has takeLeading(pattern, saga, ...args)

redux-saga 的 1.0+ 版本具有 takeLeading,它会在每个与模式匹配的 Store 中派发一个 Action 时产生一个传奇。生成一次任务后,它会阻塞,直到生成的传奇完成,然后再次开始监听模式。

之前我实现了 this solution来自 Redux Saga 的所有者,它工作得非常好——我从 API 调用中得到错误,有时会被触发两次:

You could create a higher order saga for this, which would look something like this:

function* takeOneAndBlock(pattern, worker, ...args) {
const task = yield fork(function* () {
while (true) {
const action = yield take(pattern)
yield call(worker, ...args, action)
}
})
return task
}

and use it like this:

function* fetchRequest() {
try {
yield put({type: 'FETCH_START'});
const res = yield call(api.fetch);
yield put({type: 'FETCH_SUCCESS'});
} catch (err) {
yield put({type: 'FETCH_FAILURE'});
}
}

yield takeOneAndBlock('FETCH_REQUEST', fetchRequest)

In my opinion this way is far way more elegant and also its behaviour can be easily customized depending on your needs.

关于javascript - 如何使用 Redux-Saga 避免重复的 API 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37040823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com