【问题标题】:React Native Gifted Chat + Firestore not showing messages correctly?React Native Gifted Chat + Firestore 没有正确显示消息?
【发布时间】:2021-01-20 05:05:43
【问题描述】:

我正在尝试在我的 react 本机应用程序中创建聊天功能。我正在使用 react-native-gifted-chat 并将消息保存在 Firestore 中。这是正在发生的行为:

当我发送消息时,所有消息都会重新呈现,其中一些是重复的,如您所见,到目前为止我只发送了 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. 每次组件挂载时,消息数组都会将消息推送到状态数组。
  2. 组件在我发送消息时挂载,从而重新呈现消息数组
  3. 每个消息 ID 都是唯一的,由 firebase 使用“添加”生成

请告诉我如何解决此问题!谢谢

【问题讨论】:

  • 我已经修复了“无效日期”的问题,但是看到重复和整个重新渲染的问题仍然是一个问题。
  • 更多进展:删除对 firestore 的调用以从组件中加载更多消息 Mount 没有解决问题,所以在我看来,问题在于如何将消息添加到消息数组中状态 - 现在是晚上 10 点,如果我能醒来找到解决方案,我将永远感激不尽
  • 您是如何解决无效日期问题的?
  • @R.CanserYanbakan createdAt: Moment(message[0].createdAt).format('LLL')

标签: react-native google-cloud-firestore react-native-gifted-chat


【解决方案1】:

重复是因为只有一行

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 对象仅在组件加载时创建一次,并且您只是将元素推送到该对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2020-03-31
    相关资源
    最近更新 更多