redux 创建异步Thunk:错误:对于同一操作类型,不能使用两个reducer调用addCase

k2fxgqgv  于 2023-01-05  发布在  其他
关注(0)|答案(5)|浏览(212)

将操作连接到extraReducers时发生此错误我的代码是

export const fetchCountries = createAsyncThunk(
  `country`, 
  async (organizationId: string) => {

export const saveCountry = createAsyncThunk(
  `country`,
  async ({ } => {})

const regions = createSlice({
  name,
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder.addCase(fetchCountries.pending, isFetching);
    builder.addCase(fetchCountries.rejected, error);
    builder.addCase(fetchCountries.fulfilled, (state, action) => {});

    builder.addCase(saveCountry.pending, isFetching);
    builder.addCase(saveCountry.rejected, error);
    builder.addCase(saveCountry.fulfilled, (state, {payload}) => {});

如果我运行,我会得到这个错误:第一个月

f2uvfpb9

f2uvfpb91#

发生这种情况是因为在我的操作中几乎没有 AsyncThunks 操作具有相同的***typePrefix***。
所以它肯定有不同的名字:

export const fetchCountries = createAsyncThunk(
  `getCountry`, //<------ this first argument (name) must be unique
  async (organizationId: string) => {

export const saveCountry = createAsyncThunk(
  `postCountry`,
  async ({ } => {})
bfrts1fy

bfrts1fy2#

在我的例子中,显示了相同的错误消息,但这是一个不同的错误:

.addCase(setAddress.pending, (state, action) => {
    state.setAddressStatus = 'Pending';
})
.addCase(setAddress.fulfilled, (state, action) => {
    state.setAddressStatus = 'Fulfilled';  
})
.addCase(setAddress.fulfilled, (state, action) => { // I repeated fulfilled 
    state.getAddressesStatus = 'Rejected';
    console.error(action.error);
})

我花了几分钟才发现问题,可能会帮到某人。

kx5bkwkv

kx5bkwkv3#

在CreateAsycThunk上,您提到了两个同名的字符串,它应该如下所示

export const fetchCountries = createAsyncThunk(
  `country`, 
  async (organizationId: string) => {

export const saveCountry = createAsyncThunk(
  `saveCountry`,
  async ({ } => {})

const regions = createSlice({
  name,
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder.addCase(fetchCountries.pending, isFetching);
    builder.addCase(fetchCountries.rejected, error);
    builder.addCase(fetchCountries.fulfilled, (state, action) => {});

    builder.addCase(saveCountry.pending, isFetching);
    builder.addCase(saveCountry.rejected, error);
    builder.addCase(saveCountry.fulfilled, (state, {payload}) => {});
6pp0gazn

6pp0gazn4#

createasyncthunk有两个主要参数,一个是字符串类型,另一个回调函数以API和thunk作为参数。如果切片中只有一个asyncthunk,它以“”作为数据,您可能会得到原谅,但如果您有两个或更多asyncthunk,则将对每个thunk进行检查。如果它们中两个或多个具有相似“”或“相同”的名称,则会出现令人不安的错误。“createAsyncThunk:错误:不能使用同一操作类型的两个reducer调用addCase”

6ljaweal

6ljaweal5#

这样做

const  {pending,fulfilled,rejected} = fetchCountries
    builder.addCase(pending, isFetching);
    builder.addCase(rejected, error);
    builder.addCase(fulfilled, (state, action) => {});

相关问题