【问题标题】:redux reselect selectors for relational dataredux 为关系数据重新选择选择器
【发布时间】:2016-08-29 20:21:52
【问题描述】:

选择器有两个参数,状态和道具,但是我们如何处理关系数据的选择器呢?

initialState = {
  department  :{ids:[1],byId:{name:'dep 1',id:1,parent:null}}
  sections    :{ids:[2],byId:{name:'section 1.1',id:2,parent:1}}
  subsections :{ids:[3],byId:{name:'subsection 1.1.1',id:3,parent:2}}
}

这里的部门是 n(sections) 的父级和 n(subsections) 的祖父级

<Department id="1" /> 中,我想选择部门 1 及其所有子部门。

如何在不将我需要的部门的 ID 传递给选择器的情况下编写这样的选择器?

【问题讨论】:

    标签: reactjs redux reselect


    【解决方案1】:

    您可以使用路由器(react-router)通过 url 段传递此类密钥,然后您可以访问所需的 id,即:

    mapStateToProps(state, ownProps) {
      // then get access to id here
      console.log(ownProps.params.department_id);
    }
    

    【讨论】:

      【解决方案2】:

      在这里你会找到一个实现——我希望——能回答你的第一个问题:“我们如何处理关系数据的选择器?”

      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));
      
      
      

      这个新的选择器将返回:

      如您所见,由于我没有完全理解您的商店结构,因此我对其进行了一些更改:每个域变成了一个数组,每个 id 变成了一个数字。

      希望对你有帮助... 干杯

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        • 2018-11-30
        • 2017-03-10
        相关资源
        最近更新 更多