原谅我,我是normalizr + redux的新手。我已设法规范化我的数据并创建一个减速器并最终得到:
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的新手,并没有使用所有新的语法快捷方式等,所以我怀疑还有更好的方法可以做到这一点。
是否有更简洁的方法,结果相似?
答案 0 :(得分:1)
您只能使用一个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
};
};
答案 1 :(得分:0)
lodash
(实用程序库)具有集合概念(以下是filter
函数的示例https://lodash.com/docs/4.17.4#filter。它将输入Object或Array作为输入并返回一个Array。它似乎符合您的需求。这是重构的代码:
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
};
};