我需要切换redux存储中的某些添加/删除对象。就像选中/取消选中一样。我有以下代码:
90 * (n-2) / n
4: 45
5: 54
6: 60
8: 67.5
但是现在它仅适用于添加商品到商店,当我单击选中的商品时,它应该将其从商店中删除。如何切换onclick删除/添加对象到redux存储?
答案 0 :(得分:1)
您可以尝试类似的方法。改为将ADD_ITEM更改为TOGGLE_ITEM,您可以使用Array.prototype.find之类的方法检查项目是否存在。添加(如果不存在),然后删除(如果存在):
export const click = item => ({
type: TOGGLE_ITEM,
payload: item,
});
import {
TOGGLE_ITEM,
} from "../actions";
const initialState = {
items: [],
}
export default (state = initialState, action) => {
switch (action.type) {
case TOGGLE_ITEM:
const currentItem = state.items.find(item => item.id === action.payload.id);
if (!currentItem) {
return {
...state,
items: [...state.items, action.payload],
};
} else {
const newItems = state.items.filter(item => item.id !== action.payload.id];
return {
...state,
items: [...newItems]
};
}
default:
return state;
}
};
您可能希望考虑使用单独的添加,更新和删除操作,并从组件中分派相应的操作。
答案 1 :(得分:0)
export const click = item => ({
type: TOGGLE_ITEM,
payload: item,
});
import {
TOGGLE_ITEM,
} from "../actions";
const initialState = {
items: [],
}
export default (state = initialState, action) => {
switch (action.type) {
case TOGGLE_ITEM:
// check to see if the item already in our array
// Array.some return true/false
const itemAlreadyExists = state.items.some(item => item.id === action.payload.id)
return {
...state,
// if the item already in our array filter it
// if not just add it
items: itemAlreadyExists
? state.items.filter(item => item.id !== action.payload.id)
: [...state.items, action.payload],
};
default:
return state;
}
};