从标准化数据中删除实体时,我们如何处理删除被删除实体所拥有的其他实体?例如,对于以下标准化数据,如果我要删除user1
,我还想删除user1
发布的所有帖子和评论。对于这种情况,有任何已知的方法或最佳实践吗?
{
posts : {
byId : {
"post1" : {
id : "post1",
author : "user1",
body : "......",
comments : ["comment1", "comment2"]
}
},
allIds : ["post1"]
},
comments : {
byId : {
"comment1" : {
id : "comment1",
author : "user1",
comment : ".....",
},
"comment2" : {
id : "comment2",
author : "user1",
comment : ".....",
},
},
allIds : ["comment1", "comment2"]
},
users : {
byId : {
"user1" : {
username : "user1",
name : "User 1",
}
},
allIds : ["user1"]
}
}
您可以通过多种方式查看此内容:
假设您有以下操作:
const deleteUser = userId => {
return ({
type: 'DELETE_USER',
userId
})
}
你的user
减速器可能如下所示:
const users = (state = {}, action) => {
switch (action.type) {
case 'DELETE_USER':
// delete user logic
break;
}
}
那么在Redux技术上没有任何东西可以阻止你对DELETE_USER
或posts
reducer中的comments
动作做出反应:
const posts = (state = {}, action) => {
const newState = Object.assign({}, state);
switch (action.type) {
case 'DELETE_USER':
// delete posts for action.userId
break;
}
}
如果您不喜欢上述内容,并希望保持一定程度的关注点分离,那么请考虑一种触发与动作相关的副作用的方法,例如redux-saga或redux-thunk
实施将根据图书馆而有所不同,但其想法是:
DELETE_USER
行动DELETE_USER
)
删除用户的帖子(DELETE_USER_POSTS
)
删除用户的评论(DELETE_USER_COMMENTS
)