【发布时间】: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