我的应用程序中有一个聊天消息列表,其中新项目添加到底部 . 我使用了来自另一个SO问题的一些代码,以便在添加新项目时将FlatList粘贴到底部,如下所示
<FlatList
data={messages}
renderItem={({item}) => <ChatMessage message={item}></ChatMessage>}
keyExtractor={(item, index) => index.toString()}
initialNumToRender={messages.length}
initialScrollIndex={messages.length-1}
ref={ref => this.flatList = ref}
onContentSizeChange={(contentWidth, contentHeight)=>{
this.flatList.scrollToEnd();
}}
/>
问题是当初始列表呈现时(现在只有35个项目,在数组中硬编码)它似乎只渲染了几个项目,然后向下滚动一点,然后再渲染一些,然后向下滚动一下直到最后完成渲染并坚持到底部 . 尽管添加了initialNumToRender = 并为每个结果渲染了一个非常简单的节点,但它仍然不稳定且缓慢 .
理想情况下,我想在向用户显示任何内容之前需要等待它完全渲染但是(A)他们必须等待几秒钟才能开始使用聊天室而且(B)我不认为这是怎样的Flatlist我认为元素在渲染之前必须是可见的 .
有没有更好的方法来做到这一点? (顺便在Android上测试)
编辑:添加ChatMessage组件以获得完整性
// Chat Message
import React, { Component } from 'react'
import {
StyleSheet,
ImageBackground,
Text,
View
} from 'react-native'
class ChatMessage extends Component {
constructor(props) {
super(props)
this.state = { }
}
render() {
return (
<View style={styles.chatMessage}>
<View style={styles.chatMessage_layout}>
<View style={styles.chatMessage_pic}>
<View style={styles.chatMessage_pic_image}>
<ImageBackground
source={require('./assets/images/profile-pics/example-profilr.png')}
style={styles.chatMessage_pic_image_background}
imageStyle={{ borderRadius: 40/2 }}
resizeMode="cover"
>
</ImageBackground>
</View>
</View>
<View style={styles.chatMessage_details}>
<View style={styles.chatMessage_name}>
<Text style={styles.chatMessage_name_text}>
{this.props.message.name}
<Text style={styles.chatMessage_name_time}> 24h</Text>
</Text>
</View>
<View style={styles.chatMessage_message}>
<Text style={styles.chatMessage_message_text}>{this.props.message.text}</Text>
</View>
</View>
</View>
</View>
)
}
}
export default ChatMessage;
const styles = StyleSheet.create({
chatMessage: {
paddingVertical: 10,
paddingHorizontal: 24
},
chatMessage_layout: {
flexDirection: 'row'
},
chatMessage_pic: {
width: 40,
height: 40,
marginRight: 12
},
chatMessage_pic_image: {
width: 40,
height: 40
},
chatMessage_pic_image_background: {
width: 40,
height: 40
},
chatMessage_details: {
flex: 1
},
chatMessage_name_text: {
color: '#FFF',
fontSize: 14,
fontWeight: 'bold'
},
chatMessage_name_time: {
fontSize: 11,
color: 'rgba(255,255,255,0.6)'
},
chatMessage_message: {
flexDirection: 'row',
alignItems: 'center'
},
chatMessage_message_text: {
color: '#FFF',
fontSize: 12
}
})
1 回答
如果您的项目数量较少并且想要一次渲染所有项目,那么您应该使用docs中提到的ScrollView
ScrollView :一次渲染所有元素,但如果元素数量很多则缓慢 .
FlatList :以 lazy 模式呈现项目,当它们即将出现时,在它们离开可见显示时将其删除以节省内存,使其可用于在大型列表上执行 .
对于Flatlist优化,每当渲染子项时都需要使用
PureComponent
,以便它只有shallow compares the props .同样在
keyExtractor
中使用item
的唯一ID并且不依赖于index
,因为当项目更新时index
不可靠并且可能会更改