正如问题所说,我如何过滤掉并保留两个类别在同一个列表中,但是"第三个"类别在React / redux中的单独部分?
我的组件:
{
categoryGrouping.map((category, i) =>
this.props[category].length > 0
? <Accordion title={`${trans(`HEADER_CATEGORY`)} - ${trans(`CATEGORY_${category}`)}`}
description={trans(`HEADER_TEXT_${category}`)}
expanded={category === Category.TSHIRTS}
key={i}
>
<SelectionList>
{
this.props[category].map((item, j) => <li key={j}><ListItem item={item}/></li>)
}
</SelectionList>
</Accordion>
: null
)
}
在我的容器中:
const predicateFunc = category => item => item.category === category;
const sorter = (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
const mapStateToProps = (state) => {
const list = (state.list.list || []);
return {
loaded: !!state.list.list,
[Category.UNDERWEAR]: list.filter(predicateFunc(Category.UNDERWEAR)).sort(sorter),
[Category.TSHIRTS]: list.filter(predicateFunc(Category.TSHIRTS)).sort(sorter),
[Category.JEANS]: list.filter(predicateFunc(Category.JEANS)).sort(sorter),
[Category.SWEATPANTS]: list.filter(predicateFunc(Category.SWEATPANTS)).sort(sorter),
error: state.list.error
};
};
让我们说我想要&#39;牛仔裤&#39;和&#39; SWEATPANTS&#39;在同一个列表中(但它们仍然是两个类别),但是单独的T恤&#39;和&#39; UNDERWEAR&#39;。
我多么想要:
提前致谢
答案 0 :(得分:1)
我为类别创建了一个reducer / state:
// categories = [['T-SHIRTS'], ['UNDERWEAR'], ['JEANS', 'SWEATPANTS']]
const mapStateToProps = ({categories, list}) => (
categories.map(subCategories =>
list.filter(item => subCategories.indexOf(item.category) > -1))
)
每个类别都有一个子类别数组,每个项目都有一个类别字段。
答案 1 :(得分:1)
按架构分组:
const sorter = (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
const groupCategories = ({ schema, list }) =>
Object.keys(schema).reduce(
(acc, category) =>
Object.assign(acc, {
[category]: list
.filter(item => schema[category].indexOf(item.category) > -1)
.sort(sorter),
}),
{},
);
const mapStateToProps = (state) => {
const list = state.list.list || [];
return {
loaded: !!state.list.list,
...groupCategories({
schema: {
Category1: [Category.TSHIRTS],
Category2: [Category.UNDERWEAR],
Category3: [Category.JEANS, Category.SWEATPANTS],
},
list,
}),
error: state.list.error,
};
};