我在我的 React 项目中使用 redux-toolkit。在 createSlice 的缩减器中,我想在减少最终状态之前使用状态中现有的实体数组并附加新数组。但我无法获得状态值。
这是减速器代码
export const usersSlice = createSlice({
name: "users",
initialState: initialUsersState,
reducers: {
usersCreated: (state: UsersState, action) => {
// in real, return count from the server and append the entities on front-end only?
const { count, entities } = action.payload;
const existingEntities = state.entities;
const newEntities = [...existingEntities, ...entities];
const totalCount = state.totalCount+count;
return {
...state,
entities: newEntities,
totalCount: totalCount,
listLoading: false,
error: null,
};
},
}});
当我调试 state.entites 变量时,它看起来像这样
有没有办法访问 reducer/extraReducer 中的当前状态值以根据需要重新创建状态?
因为我假设直接在 reducer 之外使用状态值是一种不好的做法。如果我错了,请指导我。
编辑
@Linda Paiste 创建的 代码沙箱 工作正常,这意味着我们可以访问 reducer 中的状态变量,但我们无法调试状态变量以更深入地挖掘状态变量目前持有的内容,因为 Redux-toolkit 是以自己的方式处理状态……从调试截图中可以明显看出
原文由 DevLoverUmar 发布,翻译遵循 CC BY-SA 4.0 许可协议
您只能引用当前切片状态。
Therefore your only options are passing the desired
entities
as action’spayload
or implementing this action as a thunkcreateAsyncThunk
and usegetState()
from its API .