【发布时间】:2018-12-24 01:12:13
【问题描述】:
我注意到库得到了很大的改进,但是我找不到如何在库中建立多对多关系。
例如,如果我有用户和 restos。我可能有“喜欢”、“访问”、“想去”等不同的多对多关系。我将如何在 normalizr.js 中对其进行规范化?
【问题讨论】:
标签: normalizr
我注意到库得到了很大的改进,但是我找不到如何在库中建立多对多关系。
例如,如果我有用户和 restos。我可能有“喜欢”、“访问”、“想去”等不同的多对多关系。我将如何在 normalizr.js 中对其进行规范化?
【问题讨论】:
标签: normalizr
您应该关注example of this in the normalizr repo。它需要mergeStrategy 和processStrategy 的组合:
import { schema } from '../../src';
const userProcessStrategy = (value, parent, key) => {
switch (key) {
case 'author':
return { ...value, posts: [parent.id] };
case 'commenter':
return { ...value, comments: [parent.id] };
default:
return { ...value };
}
};
const userMergeStrategy = (entityA, entityB) => {
return {
...entityA,
...entityB,
posts: [...(entityA.posts || []), ...(entityB.posts || [])],
comments: [...(entityA.comments || []), ...(entityB.comments || [])]
};
};
const user = new schema.Entity(
'users',
{},
{
mergeStrategy: userMergeStrategy,
processStrategy: userProcessStrategy
}
);
const comment = new schema.Entity(
'comments',
{
commenter: user
},
{
processStrategy: (value, parent, key) => {
return { ...value, post: parent.id };
}
}
);
const post = new schema.Entity('posts', {
author: user,
comments: [comment]
});
export default [post];
【讨论】: