在 React 迭代中显示最后 Child
Display Last Child in React Iteration
我正在尝试实现一个消息应用程序,暂时没有 ActionCable。当我映射所有消息时,我只想显示来自该用户的最后一条消息:我不显示来自某个用户的所有消息,而是只显示最后一条消息。我不知道如何实现。我想我可以将 key
设置为 user_id
而不是 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>
)
},
此组件位于索引页上,我正在尝试创建一个 message-like 应用程序。对 React 有什么建议吗? Rails 5用作后端。
Warning: flattenChildren(...): Encountered two children with the same key, .
. 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
是谁 sends/created 消息。
您可以尝试以下方法:
Message.where(to: current_user.id)
.order(:created_at)
.group_by(&:user_id)
.map{|_, x| x.last}
这应该给出每个 user_id
的最后一条消息(created_at
)。
只要你用的是Postgresql,都可以试试distinct on
方法:
Message.where(to: current_user.id)
.order(user_id: :asc, created_at: :desc)
.select('distinct on (user_id) *')
我正在尝试实现一个消息应用程序,暂时没有 ActionCable。当我映射所有消息时,我只想显示来自该用户的最后一条消息:我不显示来自某个用户的所有消息,而是只显示最后一条消息。我不知道如何实现。我想我可以将 key
设置为 user_id
而不是 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>
)
},
此组件位于索引页上,我正在尝试创建一个 message-like 应用程序。对 React 有什么建议吗? Rails 5用作后端。
Warning: flattenChildren(...): Encountered two children with the same key,
.
. 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
是谁 sends/created 消息。
您可以尝试以下方法:
Message.where(to: current_user.id)
.order(:created_at)
.group_by(&:user_id)
.map{|_, x| x.last}
这应该给出每个 user_id
的最后一条消息(created_at
)。
只要你用的是Postgresql,都可以试试distinct on
方法:
Message.where(to: current_user.id)
.order(user_id: :asc, created_at: :desc)
.select('distinct on (user_id) *')