2

我目前正在编写一个 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第一次尝试后退出。我需要让它继续监听状态。以上并没有我想要的那么有效。

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

更新 1、2、3、4

我还在破解一点,更接近一点:

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

1 回答 1

0

像这样的东西?

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 传递给操作。

于 2016-09-26T09:47:39.460 回答