修改 Meteor-React ToDo 列表示例以显示在某个时间范围内创建的列表项

Modify Meteor-React ToDo List Example to Display List Items Created Within a Time Range

我正在学习此处找到的 Meteor-React Todo 列表教程 https://www.meteor.com/tutorials/react/creating-an-app

根据 8.4,我们可以添加一个按钮来隐藏已勾选的待办事项。我们通过在数据库中查询检查为 true 的项目来做到这一点。

if (this.state.hideCompleted) {
        // If hide completed is checked, filter tasks
        query = {checked: {$ne: true}};
    }

如果我只想显示最近 30 分钟内创建的待办事项,即待办事项在 30 分钟后过期,我应该将查询设置为什么?

我的猜测是这样的

if (this.state.hideExpired) {
        // If hideExpired state true, only display todo items created in the last 30 minutes.
        query = {{$ne: (currentTime - createdAt) < 30 minutes}};
    }

非常接近,但您需要使用 $lte$gte 而不是 $eq:

if (this.state.hideExpired) {
  var now = new Date();
  var thirtyMinutesAgo = new Date() - 30 * 60 * 1000; //
  query = { createdAt: { $gte: thirtyMinutesAgo }}
}

请注意,此查询 不会反应。 这是因为 thirtyMinutesAgo 不是反应变量。如果您希望项目随着时间的推移从列表中动态消失,您需要让时间本身具有反应性。为此,我推荐 remcoder:chronos 包。安装该软件包后,上面的代码将变为:

if (this.state.hideExpired) {
  var now = new Date();
  var thirtyMinutesAgo = Chronos.currentTime() - 30 * 60 * 1000; //
  query = { createdAt: { $gte: thirtyMinutesAgo }}
}

Chronos.currentTime()默认每秒更新一次,thirtyMinutesAgo是一个反应变量。