我有以下数据:
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
})
})}
这是减速器的代码,它应该帮助我从状态中删除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助手函数的脚本:
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)
步骤:
- 调度一个按id删除用户的操作
function removeUser(id){
return {
type: "REMOVE_USER",
payload: id
}
}
dispatch(removeUser(1))
- 在reducer中过滤用户id与接收到的id不相等的用户,然后将新过滤的用户设置为不包括已删除用户的状态
function reducer(state, action){
switch(action.type){
case "REMOVE_USER":
return {
...state,
users: state.users.filter(user => user.id !== action.payload),
}
// other cases
}
}
祝你好运。