0

我正在使用 GiftedChat 开发一个反应原生聊天应用程序,我遇到了一个问题,即当应用程序离线时所有消息都显示在屏幕左侧。在线时,该应用会接收来自 Firebase 的消息。否则,我将从 asyncStorage 设置消息状态,如下所示:

聊天.js

const getMessages = async () => {
        try {
            let messages = await AsyncStorage.getItem('messages');
            setMessages(messages !== null ? JSON.parse(messages) : []);
        } catch (error) {
            alert(error);
        }
    };

useEffect(() => {
        navigation.setOptions({ title: name });
        NetInfo.fetch().then(connection => {
            if (connection.isConnected === false) {
                setConnection(false);
                getMessages();
            } else {
                onAuthStateChanged(auth, async user => {
                    if (!user) await signInAnonymously(auth);
                    setUser(user);
                    setMessages([]);
                    setConnection(true);
                });
                saveMessages();

                const collectionRef = collection(db, 'messages');
                const q = query(collectionRef, orderBy('createdAt', 'desc'));
                const unsubscribe = onSnapshot(q, querySnapshot =>
                    onCollectionUpdate(querySnapshot)
                );
                return unsubscribe;
            }
        });
    }, []);

    const onCollectionUpdate = querySnapshot => {
        setMessages(
            querySnapshot.docs.map(doc => ({
                _id: doc.data()._id,
                createdAt: doc.data().createdAt.toDate(),
                text: doc.data().text,
                user: doc.data().user,
            }))
        );
    };

    const renderBubble = props => {
        return (
            <Bubble
                {...props}
                wrapperStyle={{
                    right: {
                        backgroundColor: '#00bfff',
                    },
                    left: {
                        backgroundColor: 'lightgray',
                    },
                }}
            />
        );
    };

    const renderInputToolbar = props => {
        if (connection === false) {
        } else {
            return <InputToolbar {...props} />;
        }
    };

    const addMessage = () => {
        const { _id, createdAt, text, user } = messages[0];
        addDoc(collection(db, 'messages'), {
            _id,
            createdAt,
            text,
            user,
        });
    };

    const onSend = useCallback((messages = []) => {
        setMessages(prevMessages => GiftedChat.append(prevMessages, messages));
        addMessage();
        saveMessages();
    }, []);

    return (
        <View style={{ flex: 1, backgroundColor: bgColor }}>
            <Text style={{ color: '#fff', fontSize: 30, textAlign: 'center' }}>
                Connection is: {connection.toString()}
            </Text>
            <GiftedChat
                renderInputToolbar={renderInputToolbar}
                renderBubble={renderBubble}
                showAvatarForEveryMessage={true}
                messages={messages}
                onSend={messages => onSend(messages)}
                user={{
                    _id: user.uid,
                    name: user.displayName,
                    avatar: 'https://placeimg.com/140/140/any',
                }}
            />
            {Platform.OS === 'android' ? (
                <KeyboardAvoidingView behavior='height' />
            ) : null}
        </View>
    );
}

网上博览会 世博会离线

我试图通过 asyncStorage 保存用户信息并离线使用来解决此问题。无论我尝试什么,消息都会继续留在左侧。

有什么建议么?

4

0 回答 0