在这里,您会找到一个实现——我希望它能够回答您的第一个问题:“我们如何处理关系数据的选择器?”
import { createSelector } from "reselect";
const state = {
departments: [{ id: 1, byId: { name: "dep 1", id: 1, parent: null } }],
sections: [{ id: 2, byId: { name: "section 1.1", id: 2, parent: 1 } }],
subsections: [
{
id: 3,
byId: { name: "subsection 1.1.1", id: 3, parent: 2 }
}
]
};
const clone = obj => JSON.parse(JSON.stringify(obj));
const bottomUp = (...levels) =>
levels.reduce((children, parents) => {
const p = clone(parents);
const addToParent = child => {
const parent = p.find(par => par.id === child.byId.parent);
if (parent) {
if (parent.children) {
parent.children.push(child);
} else {
parent.children = [child];
}
}
}
children.forEach(addToParent);
return p;
});
const selectSubs = state => state.subsections;
const selectSecs = state => state.sections;
const selectDeps = state => state.departments;
const selectHierarchy = createSelector(
selectSubs,
selectSecs,
selectDeps,
bottomUp
);
console.log(selectHierarchy(state));
这个新的选择器将返回:
![在此处输入图像描述](https://i.stack.imgur.com/PMHp8.png)
如您所见,由于我没有完全理解您的商店结构,因此我对其进行了一些更改:每个域都变成了一个数组,每个 id 都变成了一个数字。
我希望它会有所帮助......干杯