【问题标题】:How to make the watcher saga fire a worker saga only on the first dispatch on an action pattern?如何让观察者传奇仅在动作模式的第一次调度时触发工人传奇?
【发布时间】:2020-11-27 14:00:15
【问题描述】:

如何让 watcher saga 仅在动作模式的第一次调度时触发 worker saga?

function* rootSaga() {
    yield takeEvery(CHATBOT.START, handleChatbotLoad); //I want watcher saga to trigger handleChatbotLoad only on the very first dispatch of CHATBOT.START
    yield takeEvery(CONVERSATION.ADD_QUERY, handleUserInput);
}

所以,我希望 watcher saga 仅在第一次发送 CHATBOT.START 时触发 handleChatbotLoad。我可以在started 之类的状态下设置一个标志,并且只发送一次 CHATBOT.START。 但后来我期待像takeFirst 这样的方法或类似的方法。有没有这样的方法可以做到这一点?

【问题讨论】:

    标签: redux redux-saga react-redux-i18n


    【解决方案1】:

    您可以在 root saga 中 call(或 spawnfork)一些函数,这意味着它只会在应用启动时被调用一次。并在此函数中使用take 等待动作调度:

    function* onlyVeryFirstStartWatcher() {
        const action = yield take(CHATBOT.START);
        // started, do stuff...
        yield call(handleChatbotLoad);
    }
    
    function* rootSaga() {
      yield takeEvery(CONVERSATION.ADD_QUERY, handleUserInput);
      yield call(onlyVeryFirstStartWatcher)
    }
    

    【讨论】:

    • 我不想在应用启动时调用 handleChatbotLoad。我想要的是仅在第一次发送 CHATBOT.START 时调用 handleChatbotLoad。我尝试了你上面提到的function* chatbotStartWatcher() { yield take(CHATBOT.START, handleChatbotLoad); } function* rootSaga() { yield takeEvery(CONVERSATION.ADD_QUERY, handleUserInput); yield call(chatbotStartWatcher); } export default rootSaga;,但handleChatbotLoadCHATBOT.START 的每次调度中都会被调用
    • @PraveenDass 无需将handleChatbotLoad 作为take 的第二个参数传递。之后调用它。我更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多