过滤归一化数据结构

Filtering normalized data structure

对不起,我是 normalizr+redux 的新手。我已经设法规范化了我的数据并创建了一个 reducer 并以 :

结束
state = {
    installations:{
        "1":{...},
        "2":{...}
    }
}

然后我想过滤此数据以在 UI 组件中使用到两个单独的类别(在这种情况下 installation.operator 等于当前用户)。我已经管理了一个可行的实现,但它似乎详尽无遗:

const mapStateToProps = (state, ownProps) => {
    console.log("mapStateToProps", state.installations);
    let assignedInstallations = Object.keys(state.installations)
        .filter(i => {
            return state.installations[i].operator == state.login;
        })
        .map(i => {
            return state.installations[i];
        });
    let unassignedInstallations = Object.keys(state.installations)
        .filter(i => {
            return state.installations[i].operator != state.login;
        })
        .map(i => {
            return state.installations[i];
        });
    return {
        assignedInstallations,
        unassignedInstallations,
        loginUserId: state.login
    };
};

我也是 ES6 的新手,不熟悉所有新的语法快捷方式等,所以我怀疑有更好的方法来做到这一点。

是否有更简洁的方法具有类似的结果?

你可以只用一个 reduce():

const mapStateToProps = (state, ownProps) => {
    console.log("mapStateToProps", state.installations);
    let {assignedInstallations, 
         unassignedInstallations } = Object.keys(state.installations)
          .reduce(function(acc, cur, i){
             if(state.installations[i].operator == state.login){
               acc.assignedInstallations.push(state.installations[i]);
             }else{
               acc.unassignedInstallations .push(state.installations[i]);
             }
             return acc
           }, {assignedInstallations: [], unassignedInstallations: [] })

    return {
        assignedInstallations,
        unassignedInstallations,
        loginUserId: state.login
    };
};

lodash(实用程序库)有集合的概念(这里是 filter 函数的示例 https://lodash.com/docs/4.17.4#filter)。它需要作为输入对象或数组和 returns 一个数组。它似乎适合您的需求。这是重构后的代码:

import {
  filter,
} from 'lodash'

const mapStateToProps = (state, ownProps) => {
    let assignedInstallations = filter(state.installations, installation => installation.operator == state.login);
    let unassignedInstallations = filter(state.installations, installation => installation.operator != state.login);
    return {
        assignedInstallations,
        unassignedInstallations,
        loginUserId: state.login
    };
};