我有一个可以在时间轴中呈现并插入一个组件的表单,但是我不知道如何使它按时间顺序呈现一个新的提交,以便按正确的顺序插入它。
这是我到目前为止一直在尝试的事情。
render() {
return (
<div className="timeline-container">
<ul>
{this.state.activities
.sort((a, b) => a.date > b.date)
.map((activity, i) => (
<Activity
key={i}
data={activity}
handleDelete={this.handleDelete}
/>
))}
</ul>
</div>
);
}
这是“活动”组件:
<li>
<span></span>
<div className="activity-title">{this.state.activity.title}</div>
<div className="activity-info">{this.state.activity.description}</div>
<div className="activity-location">{this.state.activity.location}</div>
<div className="activity-date">{this.state.activity.date.slice(0, 10)}</div>
<button onClick={this.handleDelete.bind(this, this.state.activity.id)}>
Delete
</button>
</li>;
目前,提交表单时,它仍会自动呈现,但未对它们进行排序。
答案 0 :(得分:1)
您应该使用new Date(date).getTime()
方法进行比较和排序。最好的方法是:
.sort(
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()
)
使用我的虚拟数据,我得到了:
我添加了更多条目,这是完整的代码:
const Activity = props => (
<li>
{props.data.title} (#{props.data.id}) ({props.data.date.split("T")[0]})
</li>
);
class App extends React.Component {
state = {
activities: [
{
id: 1,
trip_id: 5,
title: "Activity 1",
description: "Description 1",
location: "Location 1",
date: "2019-07-03T23:00:00.000Z",
pending: null,
created_at: "2019-07-28T17:49:40.269Z",
updated_at: "2019-07-28T17:49:40.269Z"
},
{
id: 2,
trip_id: 5,
title: "Activity 2",
description: "Description 1",
location: "Location 1",
date: "2019-07-05T23:00:00.000Z",
pending: null,
created_at: "2019-07-28T17:49:40.269Z",
updated_at: "2019-07-28T17:49:40.269Z"
},
{
id: 3,
trip_id: 5,
title: "Activity 3",
description: "Description 1",
location: "Location 1",
date: "2019-07-02T23:00:00.000Z",
pending: null,
created_at: "2019-07-28T17:49:40.269Z",
updated_at: "2019-07-28T17:49:40.269Z"
}
]
};
render() {
return (
<div className="timeline-container">
<ul>
{this.state.activities
.sort(
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()
)
.map((activity, i) => (
<Activity
key={i}
data={activity}
handleDelete={this.handleDelete}
/>
))}
</ul>
</div>
);
}
}
在此示例中,我使用了多个活动来向您展示如何按日期对它们进行排序。
演示:CodeSandbox
答案 1 :(得分:0)
嘿,您的日期存储为字符串,因此在比较器函数中,而不是返回布尔值,您应该像
那样为-1,1,0<body>
<h1> Tic-Tac-Toe</h1>
<div class="gameboard">
<button class="tic" id="1" onclick="clicked()"></button>
<button class="tic" id="2" onclick="clicked()"></button>
<button class="tic" id="3" onclick="clicked()"></button>
<button class="tic" id="4" onclick="clicked()"></button>
<button class="tic" id="5" onclick="clicked()"></button>
<button class="tic" id="6" onclick="clicked()"></button>
<button class="tic" id="7" onclick="clicked()"></button>
<button class="tic" id="8" onclick="clicked()"></button>
<button class="tic" id="9" onclick="clicked()"></button>
</div>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>