在这一节中,我们将学习如何从 Realm 数据库获取并展示用户播放过的音频数据。
1. 不需要使用 dva 存储所有数据
虽然在大多数场景中,我们会使用 dva 来管理应用的全局状态,但在这节功能中,我们直接从 Realm 数据库获取数据,而不需要将它存储到 dva 中。dva 更适用于多个页面共享数据或需要修改同一份数据的情况。
2. 获取数据并展示
我们使用 realm.objects 方法从数据库获取 Program 数据,并通过 FlatList 显示出来。
render() {
const programs = realm.objects<IProgram>('Program');
return (
<FlatList data={programs} renderItem={this.renderItem} />
);
}
renderItem = ({ item }: ListRenderItemInfo<IProgram>) => {
return (
<View>
<Text>{item.title}</Text>
</View>
);
}
3. 测试显示效果
在模拟器上查看效果时,如果没有数据,页面显示空白。我们需要先播放一首音频并暂停,然后刷新页面,这样数据库中就有数据了。
4. 页面布局调整
接下来,我们根据设计需求调整列表项的布局,使其包含图片、标题、时长和播放进度。
class History extends React.Component {
renderItem = ({ item, index }: ListRenderItemInfo<IProgram>) => {
return (
<View style={styles.item}>
<Image source={{ uri: item.thumbnailUrl }} style={styles.image} />
<View style={styles.content}>
<Text style={styles.title}>{item.title}</Text>
<View style={styles.iconView}>
<Icon name="icon-time" color="#999" size={14} />
<Text style={styles.text}>{getTimeString(item.duration)}</Text>
</View>
</View>
</View>
);
};
}
const styles = StyleSheet.create({
item: {
flexDirection: 'row',
marginHorizontal: 10,
borderBottomColor: '#ccc',
borderBottomWidth: StyleSheet.hairlineWidth,
},
image: {
width: 65,
height: 65,
borderRadius: 3,
margin: 5,
},
content: {
flexDirection: 'column',
justifyContent: 'center',
},
title: {
color: '#000',
},
iconView: {
flexDirection: 'row',
alignItems: 'center',
},
text: {
color: '#999',
marginLeft: 5,
},
});
5. 显示播放进度
我们还需要显示播放进度,这个值可以通过 get rate() 计算并展示。在 Program 类中,我们添加一个 rate 属性,通过当前播放时间和音频时长来计算已播放的百分比。
class Program {
currentTime = 0;
duration = 0;
static schema = {
name: 'Program',
primaryKey: 'id',
properties: {
id: 'string',
title: 'string',
thumbnailUrl: 'string',
currentTime: { type: 'double', default: 0 },
duration: { type: 'double', default: 0 },
},
};
get rate() {
return this.duration > 0 ? Math.floor(((this.currentTime * 100) / this.duration) * 100) / 100 : 0;
}
}
在列表项中,我们将播放进度显示为百分比:
<View style={styles.contentBottom}>
<Text style={styles.rate}>已播:{item.rate}%</Text>
</View>
const styles = StyleSheet.create({
rate: {
marginLeft: 20,
color: '#f6a624',
},
});
6. 模拟器查看效果
在模拟器中查看效果时,列表项现在会显示音频的标题、缩略图、时长和播放进度。
7. 总结
这一节我们实现了从 Realm 获取播放历史数据并通过 FlatList 渲染出来。通过 Program 类的 rate 属性计算播放进度,并展示在列表项中。下一节,我们将继续实现删除历史记录的功能。