renderRows如何获得最后一项的价值

时间:2019-03-14 12:21:31

标签: react-native react-native-flatlist

我正在渲染从api响应中获取的数据。 我希望能够将正在呈现的当前行与最后一行进行比较。

示例:比较项目日期和最后一项。以便插入当天的分隔符。 这只是我正在尝试做的一个简单示例。

//data    
const array = [
  {day: '3/14', name: 'item1'},
  {day: '3/14', name: 'item2'},
  {day: '3/14', name: 'item3'},
  {day: '3/15', name: 'item4'}
]    

如果新的一天,我将插入一个分隔符。目的是按天对数据进行分组。

let lastDay = null;
renderRows(item, index) {    
    //conditions
    let day = item.day;
    if(day != lastDay) daySeparator = true;

    //store last day
    lastDay = day;

    return (
        <ListItem noIndent style={style.listRow}>
        <Row style={[style.tableRow,{alignItems: 'center'}]}>
            <Text>{item.name}</Text>
        </Row>
        </ListItem>
    );
}

我的问题是renderRows不能像for循环那样工作,它会将每个项目呈现为单独的,而无法跟踪先前呈现的项目。

是否可以这样做,还是在将数组传递给RenderRows之前需要进行操作?如果是这样,foreach的最佳方法是什么?循环?

2 个答案:

答案 0 :(得分:2)

现在您的问题更加清楚了,我建议您使用类似<SectionList>的东西(请参阅doc)。 为了使用SectionList,您必须将其传递为分段数组。使用您发布的数据结构,我可以按天对项目进行分组:

const array = [
  { day: "3/14", name: "item1" },
  { day: "3/14", name: "item2" },
  { day: "3/14", name: "item3" },
  { day: "3/15", name: "item4" }
];

const grouped = array.reduce(
    (result, item) => ({
      ...result,
      [item["day"]]: [...(result[item["day"]] || []), item]
    }),
    {}
  );

const sectionedList = Object.keys(grouped).map(item => ({
    title: item,
    data: grouped[item]
}));

这将为您提供以下结构:

[
  {
    title: "3/14",
    data: [
      { day: "3/14", name: "item1" },
      { day: "3/14", name: "item2" },
      { day: "3/14", name: "item3" }
    ]
  },
  {
    title: "3/15",
    data: [{ day: "3/15", name: "item4" }]
  }
];

现在您可以在<SectionList>中使用它,例如:

<SectionList
  renderItem={({item, index, section}) => {...}}
  renderSectionHeader={({section: {title}}) => (
    <Text style={{fontWeight: 'bold'}}>{title}</Text>
  )}
  sections={sectionedList}
  keyExtractor={(item, index) => item + index}
/>

这样,您可以正确地自定义所有内容。

我真的希望这可以对您有所帮助!

答案 1 :(得分:1)

一种选择是使用初始数组中的map创建一个新数组。希望这能使您朝正确的方向发展:)

const array = [1, 2, 3, 4]

export default class App extends React.Component {
  render() {
    const newArr = array.map ((item, idx) => {
      const newItem = idx === array.length - 1 ? 'Gotta keep them separated' : item
      return <Text>{newItem}</Text>
    })
  return (
    <View>
     {newArr}
    </View>
  );
 }
}

这是工作中的expo snack