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

wydwbb8l  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(124)

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

vd2z7a6w

vd2z7a6w1#

您可以使用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

相关问题