大家好,这可能是一个愚蠢的请求,但是我想在我的应用中添加一些不错的频道顺序。
在这里,我正在渲染我的聊天频道,但是我想知道如何在渲染对象之前使用updatedAt
变量按日期拆分这些对象。就像今天,昨天或2019年2月21日(如果年龄较大)显示的标头一样。
您知道如何通过更新代码来做到这一点吗?
if (getUserChannels.length > 0) {
return getUserChannels.map(channel => (
<Channels
key={channel._id}
id={channel._id}
name={channel.jobApplication.job.name}
fullName={channel.jobApplication.job.business.name}
lastName={channel.jobApplication.user.lastName}
avatar={channel.jobApplication.job.business.logo}
lastMessage={channel.lastMessage}
updatedAt={channel.updatedAt}
onPress={() => this.onChat(channel)}
/>
));
}
答案 0 :(得分:0)
您需要先对数组进行排序,然后才能对其进行映射。您可以使用moment
来提供帮助。
getUserChannels.sort((left, right) => {
return moment.utc(left.updatedAt).diff(moment.utc(right.updatedAt))
});
答案 1 :(得分:0)
我建议您将getUsersChannels
语句之前的return
拆分为三个不同的数组,然后使用适当的标头返回所有它们。像这样:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {data: [
{
name: "Channel_1",
date: new Date("Fri Mar 01 2019 16:20:24")
},
{
name: "Channel_2",
date: new Date("Mon Feb 25 2019 13:20:24")
},
{
name: "Channel_3",
date: new Date("Thu Feb 28 2019 17:20:24")
},
]};
}
render() {
const today = new Date();
today.setHours(0,0,0,0);
const yesterday = new Date(today -1);
yesterday.setHours(0,0,0,0);
const todayChannel = this.state.data.filter(channel => channel.date >= today);
const yesterdayChannel = this.state.data.filter(channel => channel.date >= yesterday && channel.date < today);
const olderChannel = this.state.data.filter(channel => channel.date < yesterday);
return (
<React.Fragment>
<h1>Today</h1>
{todayChannel.map(el => <p key={el.name}>{el.name}</p>)}
<h1>Yesterday</h1>
{yesterdayChannel.map(el => <p key={el.name}>{el.name}</p>)}
<h1>Older</h1>
{olderChannel.map(el => <p key={el.name}>{el.name}</p>)}
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
@import url(https://fonts.googleapis.com/css?family=Montserrat);
body {
font-family: 'Montserrat', sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js"></script>
<div id='root'></div>
您可以通过创建一个函数并仅运行一次getUsersChannels
而不是运行filter
三次来改善此问题。