Redux工具包:如何使用额外的构建器处理多个api调用



我刚开始使用Redux-tolkit,对它的了解非常少,所以问题是:API调用是在额外的构建器中编写的,但如果我们必须在同一个切片中使用多个API调用,如何实现它呢?

您可以使用extraReducers插入您的api调用

import { createSlice, isAnyOf } from '@reduxjs/toolkit'
import { apiOne } from '../../app/services/apiOne'
import { apiTwo } from '../../app/services/apiTwo'
import type { RootState } from '../../app/store'
type StuffState = {
isGood: boolean
}
const slice = createSlice({
name: 'stuff',
initialState: { isGood: false },
reducers: {},
extraReducers: (builder) => {
builder.addMatcher(
apiTwo.endpoints.login.matchFulfilled,
(state, { payload }) => {
state.isGood = true
}
)
builder.addMatcher(
apiOne.endpoints.login.matchFulfilled,
(state, { payload }) => {
state.isGood = payload.isGood
}
)
},
})
export default slice.reducer

您还可以使用两个查询创建一个匹配器

import { createSlice } from '@reduxjs/toolkit'
import { apiOne } from '../../app/services/apiOne'
import { apiTwo } from '../../app/services/apiTwo'
import type { RootState } from '../../app/store'
type StuffState = {
isGood: boolean
}
const slice = createSlice({
name: 'stuff',
initialState: { isGood: false },
reducers: {},
extraReducers: (builder) => {
builder.addMatcher(
isAnyOf(apiOne.endpoints.login.matchFulfilled, apiTwo.endpoints.login.matchFulfilled),
(state, { payload }) => {
state.isGood = true
}
)
},
})
export default slice.reducer
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
const initialState = {
data1: null,
data2: null,
loading: false,
error: null,
};
// Define your API calls using createAsyncThunk
export const fetchData1 = createAsyncThunk('sliceName/fetchData1', async () => {
const response = await fetch('your/api/endpoint1');
return response.json();
});
export const fetchData2 = createAsyncThunk('sliceName/fetchData2', async () => {
const response = await fetch('your/api/endpoint2');
return response.json();
});
const mySlice = createSlice({
name: 'sliceName',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchData1.pending, (state) => {
state.loading = true;
})
.addCase(fetchData1.fulfilled, (state, action) => {
state.loading = false;
state.data1 = action.payload;
})
.addCase(fetchData1.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
})
.addCase(fetchData2.pending, (state) => {
state.loading = true;
})
.addCase(fetchData2.fulfilled, (state, action) => {
state.loading = false;
state.data2 = action.payload;
})
.addCase(fetchData2.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
});
},
});
export default mySlice.reducer;

相关内容

  • 没有找到相关文章

最新更新