我有责任创建聊天应用程序,我尝试使用React Native + RNFirebase,但是我不知道如何在发送聊天后获取最新数据,我尝试使用'scrollToEnd',但是我没有得到最新数据,向下滚动是不完整的,因此在发送最新数据后,我必须手动滚动以获取所有数据,例如,我有10个索引数组,当我发送新数据时,我想从列表中获取11个索引数据,但只向下滚动直到第10个索引,所以我必须手动滚动才能获得1个以上的数据,请更正我的脚本,否则您有其他想法。
这是我的脚本:
import React, { Component } from 'react';
import { StyleSheet, View, TextInput, FlatList, ScrollView, Dimensions } from 'react-native';
import { Container, Content, Text, Label, Button } from 'native-base';
import firebase from 'react-native-firebase';
const rootRef = firebase.database().ref();
const msgRef = rootRef.child('message');
export default class Chat extends Component {
constructor(props) {
super(props);
this.state = {
comment: '',
msg: []
}
}
componentDidMount() {
msgRef.on('value', (snapshot) => {
var dataRef = [];
snapshot.forEach((doc) => {
dataRef.push({
content: doc.toJSON().content
});
this.setState({
msg: dataRef
});
});
this.scrollView.scrollToEnd();
}, (errorObject) => {
})
}
setComment = (text) => {
this.setState({
comment: text
});
}
pressAdd() {
msgRef.push({content: this.state.comment});
}
render() {
return (
<Container>
<ScrollView ref={scrollView => this.scrollView = scrollView}>
<FlatList
style={{ flex: 1 }}
ref={(ref) => { this.flatListRef = ref; }}
keyExtractor={(item, index) => index.toString()}
data={this.state.msg}
renderItem={({ item, index}) => (
<View style={{fontSize: 14, margin: 10}}>
<Text>{item.content}</Text>
</View>
)}
/>
</ScrollView>
<View style={styles.footerChat}>
<TextInput
style={styles.formComment}
placeholder="Write a message. . ."
keyboardType='default'
autoCapitalize='none'
onChangeText={(text) => this.setComment(text)}
value={this.state.comment} />
<Button rounded style={styles.btnSend} onPress={() => this.pressAdd()}>
<Text>OK</Text>
</Button>
</View>
</Container>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#e3e6ea'
},
footerChat: {
height: 65,
backgroundColor: '#b8b9ba'
},
formComment: {
backgroundColor: '#fff',
width: '80%',
position: 'absolute',
bottom: 7,
left: 5,
borderRadius: 50,
paddingRight: 15,
paddingLeft: 15
},
btnSend: {
position: 'absolute',
right: 10,
bottom: 9,
backgroundColor: '#f4511e'
}
});
请任何人帮助我发送数据后如何在聊天列表中获取所有数据。
谢谢。