在特定日期时间调度操作

Dispatch action on a specific datetime

本文关键字:调度 操作 时间 日期      更新时间:2023-09-26

我目前正在编写一个React应用程序,我需要在我的Redux状态下监听下一个日历条目。

我正在寻求关于如何最有效和正确地做到这一点的建议。

我的calendar状态减速器包括:

entries: [
    {
        title: "Event 1",
        start: "2016-09-26T08:00:00.000Z"
        end: "2016-09-26T09:00:00.000Z"
    },
    {
        title: "Event 2",
        start: "2016-09-26T10:00:00.000Z"
        end: "2016-09-26T11:00:00.000Z"
    },
    {
        title: "Event 3",
        start: "2016-09-26T13:00:00.000Z"
        end: "2016-09-26T14:00:00.000Z"
    }
]

当下一个事件(事件1)将要发生时,我想要调度一个事件来处理这个日历条目的状态。条目减速器可以随时更新,所以我需要能够比下一个条目更早地推送条目。

我有Redux和Redux Saga可以处理这个问题。

目前我正在使用一个Redux Saga监听器,如:

export default function * watchCalendar() {
    while (true) {
        const entry = yield select((state) => state.calendar.entries[0]);
        if (entry) {
            const now = moment().startOf("minute");
            const start = moment(entry.start);
            if (now.isAfter(start)) {
                 put(CalendarActions.setActiveEntry(entry));
            }
        }
    }
}

但没有像预期的那样工作,因为while在第一次尝试后退出。我得让它继续监听国家的声音。以上并没有我想要的那么有效。

欢迎任何建议、想法或代码示例。

我还在努力,更近了一点:

export function * watchNextCalendarEntry() {
    while (true) { // eslint-disable-line no-constant-condition
        const next = yield select((state) => CalendarSelectors.getNextEntry(state.calendar));
        if (next) {
            const start = moment(next.start);
            const seconds = yield call(timeleft, start);
            yield call(delay, seconds * 1000);
            yield put(CalendarActions.setActiveCalendarEntry(next));
        }
    }
}
function * currentCalendarEntry(action) {
    try {
         while (true) { // eslint-disable-line no-constant-condition
            const entry = action.payload;
            const end = moment(entry.end);
            const seconds = yield call(timeleft, end);
            yield call(delay, seconds * 1000);
            yield put(CalendarActions.setInactiveCalendarEntry(entry));
        }
    }
    finally {
        if (yield cancelled()) {
            // e.g. do something
        }
    }
}
export function * watchCurrentCalendarEntry() {
    while (true) { // eslint-disable-line no-constant-condition
        const action = yield take(ActionTypes.SET_ACTIVE_CALENDAR_ENTRY);
        const watcher  = yield fork(currentCalendarEntry, action);
        yield take(ActionTypes.SET_INACTIVE_CALENDAR_ENTRY);
        yield cancel(watcher);
    }
}
function getTimeLeft(date) {
    return date.diff(moment().startOf("second"), "seconds");
}

像这样?

export default function* watchNextCalendarEntry() {
  takeLatest(SUBSCRIBE_CALENDAR_ENTRY, subscribeCalendarEntry);
}
function* subscribeCalendarEntry({ nextEntry }) {
  const timeLeft = moment(nextEntry.start).diff(moment());
  yield call(delay, timeLeft);
  yield put(CalendarActions.setActiveCalendarEntry(nextEntry));
}

你需要在应用程序开始时调度{ type: SUBSCRIBE_CALENDAR_ENTRY, nextEntry }动作,当条目改变时,计算并将nextEntry传递给动作。