显示React迭代中的最后一个子级 [英] Display Last Child in React Iteration

查看:128
本文介绍了显示React迭代中的最后一个子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实施一个消息应用程序,暂时没有ActionCable。当我映射所有消息时,我只想显示该用户的最后一条消息:我只显示最后一条,而不是显示某个用户的所有消息。我不知道该如何实现。我以为可以将 key 设置为 user_id 而不是 id

I'm trying to implement a message app, without ActionCable for now. When I map over all messages, I want to show only the last message from that user: instead of showing all messages, from a user, I only show the last. I do not know how to achieve that. I thought I could set the key to the user_id instead of the id.

_messagesRender: function(){
  var messages = this.props.message.map( function(m, i){
    return(
      <li key={m.user_id}>{m.body}</li>
    )
  });
  return(
    <div>{messages.length === 0 ? "No messages" : messages}</div>
  )
},

该组件位于索引页面上,我正在尝试创建类似消息的应用。有React的指针吗? Rails 5用作后端。

This component is on the index page and I'm trying to create a message-like app. Any pointers with React? Rails 5 is used as back end.


警告:flattenChildren(...):遇到两个具有相同键的孩子,。$ 2 。子密钥必须唯一。当两个孩子共享一个密钥时,只会使用第一个孩子。

Warning: flattenChildren(...): Encountered two children with the same key, .$2. Child keys must be unique; when two children share a key, only the first child will be used.

后端:

@messages = Message.where(to: current_user.id)

消息模型::id,:to,:user_id,:body

user_id 是发送/创建消息的人。

user_id is who sends/created the message.

推荐答案

您可以尝试以下操作:

Message.where(to: current_user.id)
       .order(:created_at)
       .group_by(&:user_id)
       .map{|_, x| x.last}

这应该给出最后一条消息(由 created_at )来自每个 user_id

This should give the last message (by created_at) from each user_id.

只要您使用的是Postgresql,就可以尝试区别于方法:

As long as you are using Postgresql, you can try distinct on approach:

Message.where(to: current_user.id)
       .order(user_id: :asc, created_at: :desc)
       .select('distinct on (user_id) *')

这篇关于显示React迭代中的最后一个子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆