我正在使用redux工具包。一切都还好,但现在我面临一个架构问题。
我有一个端点,我需要调用它来获取一些数据,这样我就可以进行最后的调用。
这个最后的调用响应将是我用来创建和执行一些逻辑以便调度和保存在商店中的响应,所以:
1-我应该在同一个createAsyncThunk调用中执行两个调用,然后只返回我需要的吗?
2-这个异步调用只会处理数据,我真的不需要它来保存任何东西,基于这两个调用,它会调度其他操作。我应该把这个放在哪里?
我有异步thunk可以调度其他异步thunks,没问题。
1-是的,尽管可能更难跟踪哪个api失败了
2-在我看来,如果这个暴徒和其他人住在一起会更容易
示例:
const BASE = 'user';
// some other thunk in another file, ignore implementation
const saveInLocalStorageAC = createAsyncThunk()
const fetchUserAC = createAsyncThunk(`${BASE}/fetch`, async (email, { dispatch }) => {
const id = await getIdFromEmail(email); // service
await dispatch(saveInLocalStorageAC({ loggedInUser: { id, email } })); // thunk
return id;
})
const slice = createSlice({
name: BASE,
initialState: someInitialState,
reducers: {},
extraReducers: builder => {
builder.addCase(fetchUserAC.fulfilled, (state, action) => {
// here is where I decide if I want to update the state or not
state.data = action.payload // id
})
},
})
export default slice.reducer;
如果你用某种记录器检查操作,你会看到这样的东西:
user/fetch/pending
storage/save/pending
storage/save/fulfilled
user/fetch/fulfilled