我有一个更新我的achievements
数组中的项目的开关案例,我如何为DELETE_ACHIEVEMENT
提供类似的从数组中删除文本的开关案例?
case ADD_ACHIEVEMENT:
return state.map(item => {
if (item.id === action.id) {
return Object.assign({}, item, {
achievements: [
...item.achievements,
action.text,
]
});
}
return item;
});
case REMOVE_ACHIEVEMENT:
return state.map(item => {
if (item.id === action.id) {
return Object.assign({}, item, {
// check text is in array and delete?
achievements: [
...item.achievements,
action.text,
]
});
}
return item;
});
答案 0 :(得分:0)
你可以使用Array.prototype.filter()来检查当前的成就并返回与action.text不同的元素:
case REMOVE_ACHIEVEMENT:
return state.map(item => {
if (item.id === action.id) {
return Object.assign({}, item, {
achievements: [
...item.achievements.filter(achievement => achievement !== action.text)
]
});
}
return item;
});