使用 React/Redux + Moment.JS 检查日期是否已更改

Checking if date has changed with React/Redux + Moment.JS

我有一个 React+Redux 应用程序,我使用 Moment.js 在其中显示日期。我想要一个在日期更改时 运行 的函数。

现在我有一个检查日期的功能:

  checkDate(local) {
    if (local === null) {
      localStorage.setItem('date', moment().format('MM-DD-YYYY'));
    } else if (moment(local).isBefore(moment().format('MM-DD-YYYY'))) {
      this.props.resetAll(); // This calls an action.
    }
  }

如果我手动调用它,或者在日期更改时刷新页面,它就可以正常工作。但是,我希望能够让我的应用程序 运行 和 this.props.resetAll() 独立运行,而无需刷新页面。最好的方法是什么?它应该是在 action 或 reducer 的 Redux 端发生的事情吗?我是否应该在组件生命周期的某处每隔 X 秒左右调用一次 checkDate()(如果是,在哪里)?

在此先感谢您的帮助!

我会设置超时直到 24:00,然后调用更新函数:

moment()定义为当前date/time,要得到到特定时间的差值,可以使用.diff()函数。因此,例如,如果您想要到第二天开始的毫秒数:

var msTillEndOfDay = moment().endOf('day').add(1, 'seconds').diff(moment(), 'milliseconds');

.endOf('day') 会是 23:59:59 所以你只需增加 1 秒就可以拥有第二天。

然后您只需使用特定的更新函数设置超时或调度正确的操作:

setTimeout( () => {
    this.props.dispatch({type: 'UPDATE_DATE'})
}, msTillEndOfDay);