React confirm modal 和 redux 中间件

React confirm modal and redux middleware

我也是 React 和 Redux 的新手。我想从列表中删除项目,所以我发送一个操作 deleteSelectedItems 然后我使用 redux 中间件来捕获它并显示确认。如下所示:

操作:

export const deleteSelectedItems = () => {
  return {
    type: ActionTypes.ITEM.DELETE_SELECTED,
    payload: {
      confirm: {
        message: 'Are you sure you want to delete these selected items?'
      }
    }
  }
};

中间件:

const confirmMiddleware = store => next => action => {
  if (action.payload.confirm) {
    if (confirm(action.payload.confirm.message)) {
      next(action);
    }
  } else {
    next(action);
  }
};

一切正常。现在,我不想使用 confirm() 来显示确认对话框,而是想使用我自己的 ConfirmDialog 组件。 我找到了 ,太棒了。但我很困惑如何将它们整合在一起。我想使用 confirmMiddleware 来发送显示模态的动作,但我不知道当用户在模态上单击“确定”或“取消”时如何处理。我该怎么做?

Redux 中间件并不是 UI 的正确位置,它只在您现有的实现中才真正起作用,因为 window.confirm 具有神奇的力量并且可以停止执行线程。

相反,我建议分派一个单独的操作来打开确认对话框,例如CONFIRM_DELETE_ITEMS 切换标志以指示应显示对话框,然后在单击对话框确认按钮时调度 DELETE_ITEMS 操作。

例如

function Root({ dispatch, confirmDeleteItems }) {
    return (
        <div>
            {confirmDeleteItems ? (
                <ConfirmDialog onConfirm={() => dispatch(deleteItems())} onDeny={() = dispatch(hideModal())} />
            ) : null}
            <button onClick={() => dispatch(confirmDeleteItems())}>Delete</button>
        </div>
    )
}

我设法独立地重新发明了 Dan 在那个问题中描述的模态管理技术,然后将它推得更远。我在 Implement a confirm modal using React & Redux 上写了一篇关于我的方法的文章。引用我自己的话:

I have a central component that is responsible for displaying all currently open dialogs, in the proper layout order (ie, I can have "DialogB" on top of "DialogA", etc). The component that wants to trigger showing the dialog runs an action creator that dispatches a "SHOW_DIALOG" action, with the name of the dialog component in the payload, and arbitrary additional data attached to the action. That data is added to the store, and the dialog managing component will pass that extra data to the dialog component as props when it's rendered.

I've created some generic "picker" dialogs, like ColorPicker and IconPicker. These dialogs know nothing about the rest of my app. They can take some optional bits of data in their props (such as the initially selected color value), and are also looking for a special prop with a name like "onColorSelected". The component that requested the dialog can include the entirety of another action as part of the payload, and when the dialog has its "OK" button clicked on, that new action will be dispatched along with the "return value" of the dialog.

因此,一般来说,我的建议是包含一个传递给对话框的普通操作对象,对话框可以在关闭时分派操作的副本。