我正在尝试建立一个节列表,其中列表标题是班级的名称(例如学校班级),节列表是分配给该班级的作业。
这是我的部分列表组件:
<SectionList
sections={classData}
keyExtractor={item => item.class.id}
renderSectionHeader={({ section: classProps }) => {
return (
<Text style={styles.textStyle}>{classProps.name}</Text>
);
}}
renderItem={({ item }) => {
return (
<HomeworkItem
homeworkItem={item}
deleteHomework={() => this.props.removeHomework(item)}
/>
);
}}
/>
这是获取classData
的代码:
const classData = [];
for (let x = 0; x < this.props.classes.length; x++) {
classData.push({
classProps: this.props.classes[x],
assignments: this.filterAssignments(this.props.classes[x], this.props.homework)
});
}
过滤器分配功能是这样的:
filterAssignments(c, hw) {
return hw.filter(item => item.className === c.name);
}
我收到一个错误,提示items.length
在列表的开头未定义。数据似乎正在运行。如果有人知道我如何正确执行此操作,将不胜感激。
答案 0 :(得分:1)
react native docs声明以下格式:
const DATA = [
{
title: 'Main dishes',
data: ['Pizza', 'Burger', 'Risotto'],
},
{
title: 'Sides',
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
}
];
这种格式可以通过以下循环来实现:
const classData = this.props.classes.map(item => ({
title: item.name
data: this.filterAssignments(item, this.props.homework)
}));
classData
现在可以这样传递给<SectionList
:
<SectionList
sections={classData}