如何在createSlice 的reducer 中获取状态值? [英] How can I get the state value in the reducer of createSlice?

查看:93
本文介绍了如何在createSlice 的reducer 中获取状态值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 React 项目中使用了 redux-toolkit.在createSlice 的reducer 中,我想使用状态中现有的实体数组并附加新数组,然后再减少最终状态.但我无法获得状态值.

这里是reducer代码

export const usersSlice = createSlice({名称:用户",初始状态:初始用户状态,减速器:{usersCreated: (state: UsersState, action) =>{//实际上,从服务器返回计数并仅在前端附加实体?const { 计数,实体} = action.payload;const existingEntities = state.entities;const newEntities = [...existingEntities, ...entities];const totalCount = state.totalCount+count;返回 {...状态,实体:新实体,总计数:总计数,列表加载:假,错误:空,};},}});

当我调试 state.entites 变量时,它看起来像这样

有没有办法访问 reducer/extraReducer 中的当前状态值以根据需要重新创建状态?

因为我认为在 reducer 之外直接使用状态值是一种不好的做法.如果我错了,请指导我.

编辑

由@ 创建的

解决方案

只能引用当前切片状态.

因此,您唯一的选择是将所需的 entities 作为操作的 payload 传递或将此操作作为 thunk createAsyncThunk 并使用其 API 中的 getState().

I'm using redux-toolkit in my react project. In a reducer of createSlice, I want to use the existing array of entities from the state and append the new array,before reducing the final state. But I'm unable to get the state value.

Here is the reducer code

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,
      };
    },
}});

When I debug the state.entites variable, it looks like this

Is there a way to access the current state value in reducer/extraReducer to recreate the state as per desire?

Because I assume directly working with state value outside the reducer would be a bad practice. Please guide me, if I'm wrong.

Edit

The code sandbox created by @Linda Paiste is working fine, that means we can access the state variable in reducer but we can't debug the state variable to dig deeper what is that state variable is holding at the moment, as Redux-toolkit is dealing the state in it's own way... As obvious from the debugging screenshot

解决方案

You can only reference the current slice state.

Therefore your only options are passing the desired entities as action's payload or implementing this action as a thunk createAsyncThunk and use getState() from its API.

这篇关于如何在createSlice 的reducer 中获取状态值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆