extraReducers是一个函数?
来源:10-8 【redux-toolkit】sotre配置(configureStore)与异步处理(createAsyncThunk)

程序员班吉
2024-04-12
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”
写回答
1回答
-
阿莱克斯刘
2024-04-16
在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。00
相似问题