React Native Gifted Chat + Firestore无法正确显示消息?

plupiseo  于 6个月前  发布在  React
关注(0)|答案(1)|浏览(60)

我正在尝试在我的react native应用程序中创建聊天功能。我正在使用react-native-gifted-chat并将消息保存在firestore中。下面是正在发生的行为:
x1c 0d1x的数据
当我发送一条消息时,所有的消息都重新渲染,其中一些是重复的,正如你所看到的,到目前为止我只发送了3条消息,但所有这些重复都让我想知道为什么整个事情都在重新渲染,为什么在重新渲染时会有重复。
代码:

class Chat extends React.Component {
    
    constructor(props) {
        super(props)
        this.state = {
            messages: [],
            currentUser: null,
            isLoading: true,
            messageID: ""
        }
    }
    //---------------------------------------------------------------
    async componentDidMount (){
        // get user info from firestore
        let userUID = Firebase.auth().currentUser.uid

        await Firebase.firestore().collection("users").doc(userUID).get()
        .then(doc => {
            data = doc.data()
            this.setState({
                currentUser: {
                    name: data.username,
                    avatar: data.profilePic,
                    _id: doc.id,
                },
            })
        })

        const messages = []

        await Firebase.firestore().collection("chat")
        .orderBy("createdAt", "desc")
        .limit(50)
        .onSnapshot(querySnapshot => {
            querySnapshot.forEach((res) => {
                const { 
                    user,
                    text,
                    createdAt,
                    } = res.data();
    
                    messages.push({
                        key: res._id,
                        user,
                        text,
                        createdAt,
                    });
            })

            this.setState({
                messages,
                isLoading: false, 
            });
        })
    }

    //Load 50 more messages when the user scrolls

    //

    //Add a message to firestore
    onSend = async(message) => {

        await Firebase.firestore().collection("chat")
        .add({
            user: {
                _id: this.state.currentUser._id,
                name: this.state.currentUser.name,
                avatar: this.state.currentUser.avatar,
            },
            
        })
        .then(ref => this.setState({messageID: ref.id}))

        await Firebase.firestore().collection("chat")
        .doc(this.state.messageID)
        .set({
            _id: this.state.messageID,
            text: message[0].text,
            createdAt: message[0].createdAt
        }, { merge: true })

    }

    render() {
        if(this.state.isLoading){
            return(
              <View style = {{backgroundColor: '#000000', flex: 1}}>
                <ActivityIndicator size="large" color="#9E9E9E"/>
              </View>
            )
        }   
        return (
            <View style={{backgroundColor: '#000000', flex: 1}}>
                <GiftedChat
                    showUserAvatar={true}
                    renderUsernameOnMessage={true}
                    messages={this.state.messages}
                    onSend={message => this.onSend(message)}
                    scrollToBottom
                />
            </View>
            
        )
        
    }
}

字符串
一些注解:
1.每当组件装入时,消息数组都会将消息推送到状态数组。
1.当我发送一条消息时,该组件将被挂载,从而重新呈现消息数组。
1.每个消息ID都是唯一的,由firebase使用“Add”生成。
让我知道如何解决这个问题。

v9tzhpje

v9tzhpje1#

重复是因为只有一行

const messages = []

字符串
将该行移动到侦听器内部,即onSnapShot()

await Firebase.firestore().collection("chat")
        .orderBy("createdAt", "desc")
        .limit(50)
        .onSnapshot(querySnapshot => {
            const messages = []
            // rest of your code which is having forEach loop
        });


问题是messages对象只在组件加载时创建一次,并且您只将元素推送到该对象。

相关问题