【问题标题】:React Native: GiftedChat only updating chat message if I scroll to top of screen?React Native:如果我滚动到屏幕顶部,GiftedChat 只会更新聊天消息?
【发布时间】:2020-06-15 00:06:11
【问题描述】:

我正在将 Gifted Chat 用于使用 React Native 的聊天应用程序。当我发送文本消息或图像时,代码会执行,但新消息不会出现在屏幕上,除非我滚动到聊天屏幕的顶部。如果我滚动到底部,不,如果我只滚动到一半,仍然不。只有当我滚动到屏幕顶部时它才会更新。任何人都明白为什么会发生这种情况?这是我的代码。

import React, { useState } from 'react';
import { Image, StyleSheet, Text, View, Button, FlatList, TouchableOpacity, Alert } from 'react-native';

import { GiftedChat } from 'react-native-gifted-chat';


const Conversation = (props) => {

  const chatId = props.chatId || "12345";
  const userId = props.userId || "6789";
  const [messages, setMessages] = useState([
    {
      _id: 1,
      text: 'My message',
      createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
      user: {
        _id: userId,
        name: 'Jane',
        avatar: 'https://randomuser.me/api/portraits/women/79.jpg',
      }
    },
    {
      _id: 3,
      text: 'My next message',
      createdAt: new Date(Date.UTC(2016, 5, 11, 17, 21, 0)),
      user: {
        _id: 4,
        name: 'Gerry',
        avatar: 'https://randomuser.me/api/portraits/women/4.jpg',
      },
      image: 'https://media1.giphy.com/media/3oEjHI8WJv4x6UPDB6/100w.gif',
    }
  ]);
  const d = Date.now();

  const onSend = (msg) => {
    console.log("msg : ", msg);
    const message = {
      _id: msg[0]._id,
      text: msg[0].text,
      createdAt: new Date(),
      user: {
        _id: userId,
        avatar: "https://randomuser.me/api/portraits/women/79.jpg",
        name: "Jane"
      }
    }
    const arr = messages;
    arr.unshift(message);
    setMessages(arr);
  }

  return (
    <GiftedChat
      messages={messages}
      onSend={newMessage => onSend(newMessage)}
      user={{
        _id: userId,
        name: "Jane",
        avatar: "https://randomuser.me/api/portraits/women/79.jpg"
      }}
    />
  )
}

export default Conversation;

【问题讨论】:

    标签: react-native react-native-gifted-chat


    【解决方案1】:

    想通了。 GiftedChat 要求您使用它自己的方法之一,称为append

    const onSend = (msg) => {
      console.log("msg : ", msg);
    
      // first, make sure message is an object within an array
      const message = [{
        _id: msg[0]._id,
        text: msg[0].text,
        createdAt: new Date(),
        user: {
          _id: userId,
          avatar: "https://randomuser.me/api/portraits/women/79.jpg",
          name: "Jane"
        }
      }]
    
      // then, use the GiftedChat method .append to add it to state
      setMessages(previousArr => GiftedChat.append(previousArr, message));
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-24
      • 1970-01-01
      • 2023-02-14
      • 2019-07-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      相关资源
      最近更新 更多