使用Redux切片中的条件更改状态

mutmk8jj  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(135)

在Redux Slice中随条件更改状态时遇到问题。
我有一个简单的切片,我需要编辑状态中的值,这只是在有效负载是已经在存储中的同一对象的情况下。
我的有效负载示例:

{
unix: 1667500191,
type: "lunch",
order: 2,
value: "gulash"
}

管理员会主动更改具有有效负载值的输入。因此,每次更改输入时,我都会在reducer的帮助下捕获这些值,并尝试检查给定的输入是否已经在存储中,如果是,我想更改它的值。如果不在存储中,我只想添加它。

import { createSlice } from "@reduxjs/toolkit";

const initialState = [];

export const menuSlice = createSlice({
  name: "menu",
  initialState,
  reducers: {
    add: (state, action) => {
      const { order, type, value } = action.payload;

      let newState = [...state, action.payload];

      newState?.map((item, i) => {
        if (item.type === type && item.order === order) {
          newState[i].value = value;
        }
      });

      return newState;
    },
  },
});

export const { add, remove } = menuSlice.actions;

export default menuSlice.reducer;

有人能帮帮我吗?这个好像坏了,但我不知道为什么。
谢谢

bjg7j2ky

bjg7j2ky1#

如果你的项目有一个唯一的id,这种比较检查会更容易。根据你当前的代码,如果一个项目有相同的typeorder,它就像是一个重复的项目。如果我们把这种检查移到一个实用程序函数中,可能会有助于提高可读性。

const isSameItem = (a, b) => a.order === b.order && a.type === b.type;

因此,每次我改变输入时,我都会借助reducer来捕获值,并尝试检查给定的输入是否已经在存储中,如果是,我就想改变它的值;如果不在存储中,我就想添加它。
我们可以使用数组.find().findIndex()函数来获取已有的项。如果没有已有的项,那么我们就使用.push()函数将它移到数组的末尾。

addOrUpdate: (state, action) => {
  // see if it already exists
  const extistingIndex = state.findIndex(item => isSameItem(item, action.payload));
  // add new items  
  if (existingIndex === -1) {
    state.push(action.payload);
  }
  // replace existing items
  else {
    state[existingIndex] = action.payload;
  }
}

相关问题