【问题标题】:How to determine the message rendering order in React Native Gifted Chat?React Native Gifted Chat中如何确定消息渲染顺序?
【发布时间】:2019-09-23 10:31:54
【问题描述】:

我想知道如何确定消息呈现顺序?

起初我以为它会使用 createdAt Date 对象来确定渲染,但事实并非如此。

(如您所见,它不会根据日期呈现(2019 年第一,2018 年,2017 年,2016 年和 2019 年再次)

我想知道如何修复顺序以首先显示最新消息。 我的初始消息数组如下所示:

const [messages, setMessages] = useState([
    {
      _id: 'gdfsdfasdfasdfasdfas',
      text: 'Test Test 2',
      createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 1)),
      user: {
        _id: 2,
        name: 'React Native',
        avatar: 'https://placeimg.com/140/140/any',
      },
    },
    {
      _id: 'aereraesaresraesraes',
      text: 'Test Test',
      createdAt: new Date(Date.UTC(2017, 5, 11, 17, 20, 1)),
      user: {
        _id: 2,
        name: 'React Native',
        avatar: 'https://placeimg.com/140/140/any',
      },
    },
    {
      _id: 'dasfadsfdfasfadasdasd',
      text: 'What\'s up ;)',
      createdAt: new Date(Date.UTC(2018, 5, 11, 17, 20, 1)),
      user: {
        _id: 2,
        name: 'React Native',
        avatar: 'https://placeimg.com/140/140/any',
      },
    },
    {
      _id: 'dasdasfdasfdasf',
      text: 'Hello developer',
      createdAt: new Date(Date.UTC(2019, 5, 11, 17, 20, 1)),
      user: {
        _id: 'ewrqqewrewrqrqewrewq',
        name: 'React Native',
        avatar: 'https://placeimg.com/140/140/any',
      },
    },
  ]);

【问题讨论】:

  • 你找到解决这个问题的方法了吗?

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


【解决方案1】:

这个问题对我来说也是一个真正的痛苦。我终于让它工作了。由于您已经有了 createdAt 新的 JS 日期格式,因此您只需要对数组进行排序。 react-native-gifted-chat 默认情况下不这样做。因此,在设置状态之前,请使用以下排序方法以正确的结构呈现聊天。

data.sort((a, b) => b.createdAt - a.createdAt)

【讨论】:

    【解决方案2】:

    您可以根据时间戳对对象进行排序并使用flex-direction: column-reverse。这是为了处理在聊天框中显示新消息的情况,滚动将自动聚焦在底部。

    排序: data.sort((a, b) => b.createdAt - a.createdAt) 因为我们反向渲染项目。

    保持滚动:

    display: flex;
    flex-direction: reverse
    

    【讨论】: