【问题标题】:Redux-toolkit usage with Typescript without state mutationRedux-toolkit 与 Typescript 一起使用,没有状态突变
【发布时间】:2020-08-31 14:13:21
【问题描述】:

我正在开发一个在 JavaScript 中使用 Redux-Toolkit 的 React 项目。我正在尝试将项目转移到 TypeScript 以方便调试和类型安全的好处。我的切片代码为

export const entitiesSlice = createSlice({
    name: "entities",
    initialState: initialentitiesState,
    reducers: {
      // getentityById
      entityFetched: (state, action) => {
        state.actionsLoading = false;
        state.entityForEdit = action.payload.entityForEdit;
        state.error = null;
      },
      // findentities
      entitiesFetched: (state, action) => {
        const { totalCount, entities } = action.payload;
        state.listLoading = false;
        state.error = null;
        state.entities = entities;
        state.totalCount = totalCount;
      },
      // createentity
      entityCreated: (state, action) => {
        state.actionsLoading = false;
        state.error = null;
        state.entities.push(action.payload.entity);
      },
      // updateentity
      entityUpdated: (state, action) => {
        state.error = null;
        state.actionsLoading = false;
        state.entities = state.entities.map(entity => {
          if (entity.id === action.payload.entity.id) {
            return action.payload.entity;
          }
          return entity;
        });
      },
      // deleteentities
      entitiesDeleted: (state, action) => {
        state.error = null;
        state.actionsLoading = false;
        state.entities = state.entities.filter(
          el => !action.payload.ids.includes(el.id)
        );
      },
      }
    }
  });
  

但我认为像state.somevar=updatedval 这样的任务正在做状态突变,这不好。我想用 readonly 声明我的状态接口以避免状态突变。我已经经历了Redux-Toolkit-Usage-With-Typescript,我认为应该避免状态突变,但所有代码 sn-ps 似乎都在进行状态突变。我想要这样的东西

      entityFetched: (state, action) => {
        return {
          ...state,
          actionsLoading:false,
          entityForEdit:action.payload.entityForEdit,
          error:null
        }
      }

如果我遗漏了什么或误解了状态突变的含义,请指导我。 任何关于将 TypeScript 与 React 结合使用的更广泛的建议都将受到欢迎! 非常感谢!

【问题讨论】:

    标签: javascript reactjs typescript redux redux-toolkit


    【解决方案1】:

    Redux Toolkit 的 createReducercreateSlice API 在内部使用 the Immer library,这允许您在减速器中编写“变异”语法,但会将其转化为安全且正确的不可变更新。

    请通读the new "Redux Essentials" core docs tutorial 以进一步了解 Redux 如何依赖于不可变性,以及 Immer 如何确保在您的 reducer 中编写“突变”是安全的。

    【讨论】:

    • 好的,感谢您的出色回答!但是,我仍然可以使用扩展运算符编写类似的东西来重新创建状态对象...... return { ...state, actionsLoading:false, entityForEdit:action.payload.entityForEdit, error:null }
    • 是的。 Immer 允许您要么 改变现有状态 返回一个全新的状态,因此如果您真的愿意,您仍然可以编写某种形式的嵌套展开。
    • 太棒了,谢谢!
    猜你喜欢
    • 2021-11-14
    • 2022-06-12
    • 2020-05-23
    • 1970-01-01
    • 2020-12-14
    • 2021-04-14
    • 2019-03-19
    • 2017-09-26
    相关资源
    最近更新 更多