如何使用未决承诺来处理Redux工具包中的所有API加载?
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js">
import { createSlice } from "@reduxjs/toolkit";
import { getUser, updateUser } from "./index";
import { getAllData, getData } from "../../logs/store/index";
const manageErrorAndLoading = (state, actionType, error) => {
state.loading[actionType] = true;
state.error[actionType] = error;
};
export const loadingSlice = createSlice({
name: "loading",
initialState: {
loading: false
},
reducer: {
toggleLoading: (state) => !state,
},
extraReducers: {
[getUser.pending]: () => true,
[getUser.fulfilled]: () => false,
[getUser.rejected]: () => false,
[updateUser.pending]: () => true,
[updateUser.fulfilled]: () => false,
[updateUser.rejected]: () => false,
[getData.pending]: () => true,
[getData.fulfilled]: () => false,
[getData.rejected]: () => false,
},
});
export const { toggleLoading } = loadingSlice.actions;
export default loadingSlice.reducer;
</script>
我已经使用此方法添加了加载,但效率不高。当一个API加载状态变为真时,加载在所有API上并行运行。
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js">
import { createSlice } from "@reduxjs/toolkit";
import { getUser, updateUser } from "./index";
import { getAllData, getData } from "../../logs/store/index";
const manageErrorAndLoading = (state, actionType, error) => {
state.loading[actionType] = true;
state.error[actionType] = error;
};
export const loadingSlice = createSlice({
name: "loading",
initialState: {
loading: false
},
reducer: {
toggleLoading: (state) => !state,
},
extraReducers: {
[getUser.pending]: () => true,
[getUser.fulfilled]: () => false,
[getUser.rejected]: () => false,
[updateUser.pending]: () => true,
[updateUser.fulfilled]: () => false,
[updateUser.rejected]: () => false,
[getData.pending]: () => true,
[getData.fulfilled]: () => false,
[getData.rejected]: () => false,
},
});
export const { toggleLoading } = loadingSlice.actions;
export default loadingSlice.reducer;
</script>
I have used this method to add loading but its not efficient. the loading is running parallel on all api, when one api is loading state gets true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
ISPENDENG
也可以用iSrejected
和iSfulfield
替换。In the RTK matching utilities there is the
addMatcher
utility, which can catch all the pending, fulfilled and/or rejected promises. For example:isPending
can be replaced also withisRejected
andisFulfilled
.