redux工具包的状态过滤器有问题



我试图使用redux Toolkit将bill添加到billItems状态,但我没有我希望在billItems中有多个具有相同Id的相同账单。每张账单都是{billId: 5, billName: "string"}。我做了很多尝试,但都没有我想要的效果

第一次尝试

export const billSlice = createSlice({
name: "bill",
initialState: {
billItems: [],
},
reducers: (state, action) => {
const arr = [...state.billItems];
if (arr.length === 0) {
state.billItems = [...arr, action.payload];
} else {
const filteredArr = arr.filter(
(item) => item.productId !== action.payload.productId
);
state.billItems = [...filteredArr, action.payload];
}
},
});

有了这个尝试,当我可以调度它只是改变以前的账单和替换为不需要的新结果

第二次尝试我决定将lastBill保留在initialstate中,使用多个相同的账单获取所有billItems状态然后在选择器中使用lastBill属性过滤它。在选择器中像这样

export const bSlice = createSlice({
name: "bill",
initialState: {
lastBill: {},
billItems: [],
},
reducers: (state, action) => {
state.billItems = [...state.billItems, action.payload]
});

选择器是

const billItems = useSelector(state => {
const arr = state.billItems
const lastBill = state.lastBill
const lastBill_Id = state.lastBill.lastBillId
if(arr.length === 0){
return [...arr, lastBill]
}else{
// I filter to obtain a new array whithout any instance of the lastBill
const filteredArr = arr.filter(item => item.billId !== lastBill_Id)
// I push now the lastBill to be sure that it is unique in the array and return it
return [...filteredArr, lastBill]
}
} )

但是在这个尝试中,当我用相同的账单填充商店时,商店保存它,然后我在状态billItems中有许多相同的账单,这不是需要的结果

有件事我不明白。我需要你的帮助

经过多次研究,我对此有一个问题。问题是javascript中对象的引用。我像这样在账单上找零钱。

[add_to_billItems_action.fulfilled]: (state, action) => {
let arr = state.billItems;
if (arr.length === 0) {
// I make a copy of arr and modify billItems. At that time arr and billItems have the same payload

state.billItems = [...arr, action.payload];

arr = state.billItems;
} else {
let filteredArr = arr.filter((item) => item.id !== action.payload.id);
state.billItems = [...filteredArr, action.payload];
}