繁体   English   中英

如何从 redux state javascript 中的另一个阵列中删除一个阵列

[英]How to remove an array from another array in redux state javascript

我有以下数据:

removed_users = [1]

userProfile = [{id:1 , user:{id:1,username:test}} ,
               {id:2 , user:{id:2,username:test2}} ,]

我希望做什么:我希望能够根据数组removed_users从 userProfile 中删除正确的对象。 我已经尝试了下面的代码,但它没有从数组中删除它

state.project['userProfile'].filter(function(user) {
                                                    return !action.payload.find(function(removed) {
                                                            return removed === user.user.id
                                                                    })
                                                                })}

这是应该帮助我从 state 中删除removed_users的减速器的代码

        case 'user_remove': return (updateObject(state, {
        project: {...state.project , ['users']:  state.project['userProfile'].filter(function(user) {
                                                                    return !action.payload.find(function(removed) {
                                                                    return removed === user.user.id
                                                                    })
                                                                })}
    }))

这是 updateObject 助手 function 的脚本:

export const updateObject = (oldObject, updatedProperties) => {
return {
    ...oldObject,
    ...updatedProperties
}

}

您的过滤器有误。 使用这样的表达式:

userProfile.filter((user)=>!removed_users.includes(user.id))

在操场上查看完整示例: https://jscomplete.com/playground/s534466

试试这个删除用户:

 const userProfile = [ {id:1, user:{id:1,username:"t1"}}, {id:2, user:{id:2,username:"t2"}}] const arr= [1]; const filtered = userProfile.filter(({user})=>.arr.includes(user;id)). console.log(filtered)

脚步:

  1. 通过用户的 id 调度删除用户的操作。
function removeUser(id){
   return {
     type: "REMOVE_USER",
     payload: id
   }
}
dispatch(removeUser(1))
  1. 在 reducer 中过滤用户 id 与接收到的 id 不相等的用户。 然后在 state 中设置新的过滤用户,其中不包括已删除的用户。
function reducer(state, action){
   switch(action.type){
     case "REMOVE_USER":
        return {
          ...state,
          users: state.users.filter(user => user.id !== action.payload),
        }
     // other cases
   }
}

祝你好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM