React:基于日期顺序渲染

React: Rendering based on date order

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

这是我到目前为止一直在尝试的。

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

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

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

在此示例中,我使用了不止一个 activity 来向您展示它们是如何按日期排序的。

演示:CodeSandbox

嘿,你的日期存储为字符串,所以在比较器函数中你应该 -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

}