你好所以我想让我的 reducer 能够删除属性数组中的项目。我正在处理看起来像这样的用户状态。
users = {
'testUser1:{
id:'',
name:'',
favorites:['oranges','apples'],
lists:{
myList:[]
}
},
}
我希望能够从我的 reducer 中的收藏夹属性中删除项目。
到目前为止,这是我的 reducer
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'
) */
}
}
}
最佳答案
好的。根据我所阅读的内容,我假设您的相关 reducer 操作返回了有问题的 Entire User 对象。
因此,我假设 ADD_FAVORITE 的操作将返回用户对象作为响应以及收藏夹数组的字符串格式的收藏夹元素的名称?
因此对于 DELETE_FAVORITE 操作,它应该返回 User 对象以及要删除的收藏夹对象的字符串值。
所以我看到你尝试过,过滤器应该在这种情况下起作用。
case DELETE_FAVORITE:
return{
...state,
[action.authedUser]:{
...state[action.authedUser],
favorites: action.authedUser.favorites.filter(word => word != action.favorite),
}
}
关于javascript - Redux:帮助过滤/删除我的 reducer 中属性的数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62760488/