在将项目添加到 Redux 中的项目数组之前,我如何检查它是否不存在

how can i check if an item does not exist before adding it to Array of items in Redux

我试图在添加项目之前检查项目是否不在项目数组中,但我收到错误 TypeError:无法读取未定义的属性(读取 'indexOf')请问我在这里做错了吗,有人可以帮助我吗?

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

const initialState = {
  items: [],
};

export const basketSlice = createSlice({
  name: 'basket',
  initialState,
  reducers: {
    addToBasket: (state, action) => {
      let prevItems = state.items.indexOf(action.payload) > -1;
      let newItems = [...state.items];

      if (prevItems) {
        newItems = newItems.filter((id) => id !== action.payload);
      } else {
        newItems.push(action.payload);
      }

      return {
        ...state.items,
        newItems,
      };
    },
  },
});

export const { addToBasket } = basketSlice.actions;

export const selectItems = (state) => state.basket.items;

export default basketSlice.reducer;

我认为问题出在您的 return 语句上。因为它用对象覆盖了整个状态。


return {
    items: newItems
};

试试这个解决方案。

let items=['1','2','3']
let newItems=[];
if (!items.includes(action.payload) || items.length==0 ) {
  // if item does not exists then add that item OR if items array is empty
  const newArr = [...items,action.payload]
  newItems.push(newArr);
} else {
  // else return actual array
  newItems = items;
}
return newItems;