从标准化数据中删除实体时,我们如何处理删除被删除实体所拥有的其他实体?例如,对于以下规范化数据,如果我要删除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"]
}
}
答案 0 :(得分:0)
您可以通过多种方式查看此内容:
我们假设你有以下行动:
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
缩减器中的comments
操作做出反应:
const posts = (state = {}, action) => {
const newState = Object.assign({}, state);
switch (action.type) {
case 'DELETE_USER':
// delete posts for action.userId
break;
}
}
如果你不喜欢上述内容,并希望保持某种程度的关注点分离,那么请考虑一种触发与行为相关的副作用的方法,例如redux-saga或{ {3}}
实施将根据库而有所不同,但想法是:
DELETE_USER
行动DELETE_USER
)DELETE_USER_POSTS
)DELETE_USER_COMMENTS
)