如何将Object Key呈现为SectionList标头?这样我就可以在《今日的昨天》的基础上制作章节了。下面我提供了对象,在Lodash的帮助下,对象按日期分组,日期使用即时格式化
代码链接:小吃博览会
对象:
{
"18-Apr-2021": [
{
"id": 1,
"title": "Spotify Premium",
"amount": -9.99,
"payType": "Subscription",
"time": "5:22 PM",
"date": "2021-04-18T08:38:00.889Z"
},
{
"id": 2,
"title": "Starbucks",
"amount": -32,
"payType": "Food",
"time": "3:34 PM",
"date": "2021-04-18T08:38:00.889Z"
}
],
"04-Oct-2021": [
{
"id": 4,
"title": "TopUp",
"amount": 1500,
"payType": "Income",
"time": "Ready to use",
"date": "10-4-2021"
},
{
"id": 5,
"title": "Loving Hut Vegan",
"amount": -32,
"payType": "out Expenses",
"time": "10:47 AM",
"date": "10-4-2021"
},
{
"id": 6,
"title": "Market",
"amount": -138.74,
"payType": "Daily Shopping",
"time": "10:47 AM",
"date": "10-4-2021"
}
],
"04-Aug-2021": [
{
"id": 7,
"title": "Grocery Market",
"amount": -138.74,
"payType": "Daily Shopping",
"time": "10:47 AM",
"date": "08-04-2021"
}
]
}
我使用了moment和lodash来格式化数据
我尝试过的代码:
import _ from 'lodash';
import * as React from 'react';
import { Text, View, StyleSheet,SectionList } from 'react-native';
import moment from 'moment';
import Constants from 'expo-constants';
import List from './List'
import {statementHistory} from './data'
export default function App() {
let group = _.groupBy(statementHistory, e => moment(e.date).format("DD-MMM-YYYY"))
return (
<View>
<SectionList
sections={group}
renderItem={(item) => <List item={item}/>}
renderSectionHeader={(section) => console.log("section",section)}
keyExtractor={(item, index) => index}
/>
</View>
);
}
您在节列表中使用了错误的数据。部分列表需要一个对象数组,该数组的标题为标题,数据数组为列表。
[ {
title:"Header",
data:["Data1","data3"]
},
{ ... }, { ... } ]
对于您的数据集,您需要将数据修改为
...
let group = _.groupBy(statementHistory, e => moment(e.date).format("DD-MMM-YYYY"))
// modify dataset of section List
group = Object.keys(group).map((item) => {
return {
title: item,
data: group[item],
};
});
console.log(group);
...
您可以参考这里:https://reactnative.dev/docs/sectionlist