Skip to main content

Command Palette

Search for a command to run...

redux-saga 中对按需打开/关闭对话框的一个实践

Updated
1 min read

这里使用的组件是 ant design

我们在实践过程中很有可能会遇到执行完成某个异步操作之后需要弹出对话框进行确认/取消操作然后执行后续行为的情况. 但是在 redux-saga 中, 因为一系列行为都是使用 generator 实现的, 而主体逻辑又被包含在了一个又一个的 saga 中, 无法人为地去执行 yield, 使得实现这个需求有些困难.

因此,我们需要把 Modal.confirm() 转换为 Promise:

export const showConfirm = ({ title, content }) => {
  return new Promise((resolve, reject) => {
    Modal.*confirm*({
      title,
      content,
      onOk() {
        return resolve(true)
      },
      onCancel() {
        return reject(false)
      },
    })
  })
}

之后就可以通过 yield call() 来调用它了,通过 catch 来处理 cancel 时的事件, 具体代码如下:

export const showConfirm = ({ title, content }) => {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title,
      content,
      okText    : `确认`,
      cancelText: '取消',
      onOk() {
        return resolve(true)
      },
      onCancel() {
        return reject(false)
      },
    })
  })
}

// saga
function* show() {
  try {
    yield call(showConfirm)
    yield put(resolveAction())
    return true
  } catch(e) {
    yield put(rejectAction())
    return false
  }
}

Tips: 在声明了一个 saga 之后,是可以通过 call 方法获得返回值的,但是 通过 fork 方法得到的是一个 task 对象

22 views

More from this blog

Al's blog

21 posts