请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

extraReducers是一个函数?

export const productDetailSlice = createSlice({
    name: "productDetail",
    initialState,
    reducers: {
      
    },
    extraReducers: {
        [getProductDetail.pending.type]: (state) => {
            // return {...state, loading: true}
            state.loading = true
        },
        [getProductDetail.fulfilled.type]: (state, action) => {
            state.loading = false
            state.data = action.payload
            state.error = null
        },
        [getProductDetail.rejected.type]: (state, action: PayloadAction<string | null>) => {
            state.loading = false
            state.error = action.payload
        }
    },
})

上面代码extraReducers报错,我进入extraReducers的定义,看到是其是一个函数:

// 文件:node_modules/@reduxjs/toolkit/dist/createSlice.d.ts
   extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;
    /**
     * A map of selectors that receive the slice's state and any additional arguments, and return a result.
     */
    selectors?: Selectors;
}

我的tkt版本: “redux-toolkit”: “^1.1.2”

正在回答 回答被采纳积分+3

1回答

阿莱克斯刘 2024-04-16 12:27:00
在React Redux中,extraReducers不是一个方法,而是一个选项,你可以在使用createSlice时配置它。extraReducers允许你的slice响应在其他地方定义的action,而不是创建新的action creator(参考资料: https://stackoverflow.com/questions/66425645/what-is-difference-between-reducers-and-extrareducers-in-redux-toolkit)。这通常用于处理异步action,比如那些由createAsyncThunk生成的action,或者是来自其他slice的action。(参考资料: https://stackoverflow.com/questions/66425645/what-is-difference-between-reducers-and-extrareducers-in-redux-toolkit)

例如,如果你有一个异步的Thunk action,你可以在extraReducers中处理它的pending、fulfilled和rejected状态。这是一个使用extraReducers的例子:

const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await userAPI.fetchById(userId);
    return response.data;
  }
);

const usersSlice = createSlice({
  name: 'users',
  initialState: { users: [], loading: false },
  reducers: {
    // 你的reducers逻辑
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchUserById.pending, (state) => {
        state.loading = true;
      })
      .addCase(fetchUserById.fulfilled, (state, action) => {
        state.loading = false;
        state.users = action.payload;
      })
      .addCase(fetchUserById.rejected, (state) => {
        state.loading = false;
      });
  }
});

在这个例子中,extraReducers使用了一个builder参数,它提供了addCase方法来响应特定的action类型,并更新state。这样,你就可以在slice外部定义action,然后在slice内部响应这些action,而不需要为每个action创建一个新的action creator。
0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信