在 redux-saga 的嵌套函数中调度动作

dispatching actions within nested functions in redux-saga

当用户提交表单时,我希望他们收到多个模式提示。

基本结构: 我的应用程序设置为显示模态,您所要做的就是分派一个动作,模态主体作为动作的有效负载。

dispatch({type: SHOW_MODAL, payload: <MyModal />})

当用户提交表单时,一个由 saga 拾取的动作被调度,所以现在我们进入了 saga 领域。我想做的是在表单实际提交到后端之前,让用户依次显示几个模式。

// mySaga.js

function* submitForm() {
  // show a modal
  // then show another modal
  // then submit the form
}

最好的方法是什么?对我来说最有意义的是使用承诺。

// mySaga.js
function* submitForm() {
 yield call(() => {
   new Promise( resolve => {
     yield put({type: SHOW_MODAL, payload: <MyModal onClick={resolve} />})
   })
 })
 ...
 // add as many more modals as I'd like
 ...
 yield call(myApiCall)
}

上面的问题是您不能在该 promise 函数中使用 yield,因为它不是生成器。我所需要的只是一种在 saga 中正常发送动作的方法,但在整个互联网上看,这似乎一点也不微不足道。

我是不是遗漏了一些关于 sagas 的东西?最好的方法是什么?

我建议稍微修改一下你的程序。

分派 <Modal/> 组件来存储不是一个好主意。虽然你可以在 store 中存储组件,但是很难将正确的 props 传递给组件。

我建议存储一个变量,例如 firstModalOpened,它将控制是否显示模态。您可以在 saga 中设置此变量并等待更改此变量的操作。

// mySaga.js
function* submitForm() {
  yield put({type: SHOW_MODAL, firstModalOpened: true});
  take('FIRST_MODAL_CLOSED');   // Await for modal close action
   ...
  // add as many more modals as I'd like
   ...
  yield call(myApiCall)
}

在 React 中,<Modal/> 组件可以按如下方式使用

<Modal open={props.firstModalOpened} onClose={() => dispatch({type: 'FIRST_MODAL_CLOSED'})}/>

如果您有多个将同时打开的模式,您可以多次调用 put,然后等待所有关闭操作到达,然后再继续 yield call(myApiCall)

yield put({type: SHOW_MODAL, firstModalOpened: true});
yield put({type: SHOW_MODAL, secondModalOpened: true});
yield all([
  take('FIRST_MODAL_CLOSED')
  take('SECOND_MODAL_CLOSED')
]);