Display Last Child in React Iteration

冷暖自知 提交于 2019-12-11 07:33:35

问题


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>
  )
},

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.

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.

Back end:

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

Message model: :id, :to, :user_id, :body

user_id is who sends/created the message.


回答1:


You can try the following:

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

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

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) *')


来源:https://stackoverflow.com/questions/37862226/display-last-child-in-react-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!