Javascript Redux:帮助筛选/删除my reducer中属性的数组项
您好,我想让我的reducer能够删除属性数组中的项。我使用的用户状态如下所示Javascript Redux:帮助筛选/删除my reducer中属性的数组项,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,您好,我想让我的reducer能够删除属性数组中的项。我使用的用户状态如下所示 users = { 'testUser1:{ id:'', name:'', favorites:['oranges','apples'], lists:{ myList:[] } }, } 我希望能够从我的reducer中的favorites属性中
users = {
'testUser1:{
id:'',
name:'',
favorites:['oranges','apples'],
lists:{
myList:[]
}
},
}
我希望能够从我的reducer中的favorites属性中删除项目
这是到目前为止我的减速机
function usersReducer(state={},action){
switch(action.type){
case RECEIVE_USERS:
return{
...state,
...action.users,
}
case ADD_FAVORITE:
return{
...state,
[action.authedUser]:{
...state[action.authedUser],
favorites:
state[action.authedUser].favorites.concat([action.favorite])
}
}
case DELETE_FAVORITE:
/*const newArray = Object.values(action.authedUser.favorites).filter((item)=>
item !== 'oranges'
) */
}
}
}
超近距离
const newFavorites = state[action.authedUser].favorites.filter(item =>
item !== action.favorite
);
return {
...state,
[action.authedUser]: {
...state[action.authedUser],
favorites: newFavorites,
}
};
您希望筛选出与
action.favorite
(或您决定如何命名)匹配的项目,然后将该新数组设置为用户的收藏夹。确定。根据我所读到的内容,我假设您的相关reducer操作会返回整个用户对象
因此,我假设ADD_FAVORITE的操作将返回User对象作为响应,以及favorites数组的字符串格式的FAVORITE元素的名称
因此,对于DELETE_FAVORITE操作,它应该返回用户对象以及要删除的FAVORITE对象的字符串值
正如我看到的,在这种情况下,过滤器应该可以工作
case DELETE_FAVORITE:
return{
...state,
[action.authedUser]:{
...state[action.authedUser],
favorites: action.authedUser.favorites.filter(word => word != action.favorite),
}
}