javascript - Redux:帮助过滤/删除我的 reducer 中属性的数组项

标签 javascript reactjs redux react-redux

你好所以我想让我的 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/

相关文章:

redux - 如何为 combineReducers 提供正确的状态切片

javascript - JavaScript 中的同步调用不起作用

javascript - AngularJS - 绑定(bind)元素以模糊未触发

javascript - 所有 Schema 的 Schema 方法 - Mongoose 方法继承

javascript - Angular Material md-select 不绑定(bind)

reactjs - React Redux extraReducers 操作负载未知类型

javascript - 如何在桌面上调整 CSS,但在平板电脑的另一个元素下方

javascript - MIME 类型 ('text/html' ) 不是受支持的样式表 MIME 类型

javascript - ReactJS - 在所有数据输入状态后将我的加载更改为 false

javascript - 如果使用 fetch 从服务器检索,则未设置 Redux 初始状态