【问题标题】:FindIndex() removing items from redux storeFindIndex() 从 redux 存储中删除项目
【发布时间】:2021-09-07 03:40:55
【问题描述】:

在使用 RTK Query 时,我尝试构建删除并添加到收藏功能。我有麻烦,因为我可以添加到状态。但是.FindIndex() 上的删除部分总是返回 -1 它是否错误地使用了这个函数?

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

const initialState = {
  value: false,
  cardFavId: [],
};

export const favouriteSlice = createSlice({
  name: "favourite",
  initialState,
  reducers: {
    makeFav: (state, action) => {
      state.value = !state.value;
      state.cardFavId = [...state.cardFavId, action.payload];
    },

    removeFav: (state, action) => {
      console.log(action.payload, "payload remove pressed");
      const index = state.cardFavId.findIndex(
        (cardItem) => cardItem.id === action.payload
      );

      let newCardFav = [...state.cardFavId];
      console.log(`Index Value ${index}`);

      if (index >= 0) {
        //itemCard has been Faved.. remove it.
        newCardFav.splice(index, 1);
      } else {
        // Do nothing
        console.warn("Cannot remove as its not been fav ");
      }
      state.cardFavId = newCardFav;
    },
  },
});

// Action creators are generated for each case reducer function
export const { makeFav, removeFav } = favouriteSlice.actions;

export default favouriteSlice.reducer;

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    首先,您的findIndex 回调不正确,因为您需要将项目的id 与action.payload.id 进行比较,而不仅仅是action.payload,因为payload 是一个对象。

    其次,从数组中删除项目的一种更简单的方法(虽然有时效率较低,但更容易编写)是像

    state.cardFav = state.cardFav.filter(cardItem => cardItem.id !== action.payload.id)
    

    意思是,您只保留 id 与您要删除的项目不同的项目

    【讨论】:

      猜你喜欢
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2016-10-13
      • 2019-11-26
      • 2019-02-15
      • 1970-01-01
      • 2021-11-23
      相关资源
      最近更新 更多