Я использую React Native и Firebase для создания приложения для чата. Проблема, с которой я столкнулся, заключается в том, что мой компонент React повторно отрисовывается в бесконечном l oop. Я получаю доступ к экрану, используя StackNavigator
, и могу нажать кнопку «Назад», чтобы отключить этот компонент и остановить бесконечные повторные отрисовки. Мой код ниже. Может ли кто-нибудь помочь мне понять, как предотвратить бесконечную рендеринг?
import React, { useState, useEffect } from 'react';
import { StyleSheet } from 'react-native';
import * as firebase from 'firebase';
import firestore from 'firebase/firestore';
import { GiftedChat } from 'react-native-gifted-chat'
const Conversation = (props) => {
useEffect(() => {}, []);
const chatId = props.chatId;
const userId = props.userId;
const otherPerson = props.other;
const [messages, setMessages] = useState([]);
const d = Date.now();
firebase.firestore().collection("chatMessages").doc("chatMessages").collection(chatId).get()
.then((snapshot) => {
console.log("snapshot");
if (snapshot.exists) {
const data = snapshot.data();
const keys = Object.keys(data);
let arr = keys.map((item) => {
const messageId = item;
const text = snapshot[messageId].text;
const createdAt = snapshot[messageId].timestamp;
const obj = {
_id: messageId,
text: text,
createdAt: createdAt
};
return obj;
});
setMessages(previousArr => GiftedChat.append(previousArr, arr));
}
})
.catch((error) => {
console.log("error : ", error);
});
firebase.firestore().collection("chatMessages").doc("chatMessages").collection(chatId)
.where("otherPerson", "==", otherPerson)
.onSnapshot((updatedSnapshot) => {
let arr2 = [];
updatedSnapshot.forEach((doc) => {
arr2.push(doc.data());
});
setMessages(previousArr => GiftedChat.append(previousArr, arr2));
});
return (
<GiftedChat
messages={messages}
onSend={newMessage => onSend(newMessage)}
animated={ true }
user={{
_id: userId,
name: "Jane Doe",
avatar: "https://randomuser.me/api/portraits/women/79.jpg"
}}
/>
)
}
const styles = StyleSheet.create({
button: {
width: "80%",
marginVertical: 8
},
view: {
flex: 1,
height: "100%",
marginVertical: 50
}
});
export default Conversation;