2

我有一个呈现组件并将其插入时间轴的表单,但我不知道如何让它按时间顺序呈现新的提交,以便它以正确的顺序插入。

这是我迄今为止一直在尝试的。

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

这是 Activity 组件:

<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>;

目前,提交表单时它仍会自动呈现,但不会对它们进行排序。

4

2 回答 2

2

您应该使用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>
    );
  }
}

在此示例中,我使用了多个活动来向您展示它们是如何按日期排序的。

演示:代码沙盒

于 2019-07-28T18:17:33.267 回答
0

嘿,您的日期存储为字符串,因此在比较器函数中而不是返回布尔值,您应该像 -1, 1, 0

// where a and b are strings.
function camp(a, b){
    If (a>b) {
       return 1
}
if ( a<b){
     return -1
}

// in case of equal 
return 0

}
于 2019-07-28T18:20:22.767 回答