【问题标题】:Callback within redux sagaredux 传奇中的回调
【发布时间】:2019-12-04 06:29:32
【问题描述】:

我在我的传奇中使用 Ant Design 的 Modal.confirm,我试图传递一个回调,该回调在一个模式参数中调度一个动作。

我尝试使用this post 中的频道解释,但我认为我对如何解决此问题的想法有误。

function* editCustomer(action) {
  try {
let postBody = { overwrite: action.payload.overwrite }
    let customerResponse = yield call(_api.execute, url, "POST", postBody);
  } catch (error) {
    if (statusCode === 409) {
     /// duplicate data, pass in overwrite
      Modal.confirm({
        title: 'Sample title',
        onOk: () => {
          editCustomerChannel.put(_customerActions.editCustomer({ 
            overwrite: true 
         }))
        }
      })      

    } else {
      yield put({ type: "CUSTOMERS__EDIT_CUSTOMER_FAILED" });
    }
  }
}

/// CustomerSagas
export default [
  takeEvery('CUSTOMERS__SET_CUSTOMER_OWNER', setCustomerOwner),
];
export default function* rootSaga() {
    yield all([...CustomersSagas]);
}

我的示例代码显示了editCustomer 传奇。我期待 _api.execute 在 try/catch 块中抛出错误,然后调用 Modal.confirm 并使用回调再次调用 editCustomer,并将 overwrite 键设置为 true。我的问题是我无法在回调中调度editCustomer

我应该如何解决这个问题?

谢谢!

【问题讨论】:

  • 如何在组件中调度操作?

标签: javascript redux callback redux-saga antd


【解决方案1】:

我会尝试直接使用store.dispatch()

# Wherever your configured store is
import { store } from './store' 

function* editCustomer(action) {
  try {
let postBody = { overwrite: action.payload.overwrite }
    let customerResponse = yield call(_api.execute, url, "POST", postBody);
  } catch (error) {
    if (statusCode === 409) {
     /// duplicate data, pass in overwrite
      yield call([Modal, 'confirm'], {
        title: 'Sample title',
        onOk: () => {
          store.dispatch(_customerActions.editCustomer({ 
            overwrite: true 
         }))
        })
      })      

    } else {
      yield put({ type: "CUSTOMERS__EDIT_CUSTOMER_FAILED" });
    }
  }
}

请注意,我还将 Modal.confirm({...}) 替换为 yield call([Modal, 'confirm'], ...),这与您的问题没有直接关系,但通常是在 saga 中对外部 API/工具/等进行函数调用的正确方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    相关资源
    最近更新 更多