getUserConfirmation 提示带历史重定向的 React Router

lou*_*ros 5 history.js reactjs

当离开表单状态已更改的页面时,我使用createBrowserHistorywith来处理确认用户验证:getUserConfirmation

import { createBrowserHistory } from 'history';
import store from './store';
import { displayPrompt } from './ui/navigation-prompt/navigationPromptDucks';

export default createBrowserHistory({
  getUserConfirmation(message, callback) {
    store.dispatch(displayPrompt(message, callback));
  },
});
Run Code Online (Sandbox Code Playgroud)

它运作良好:当我开始编辑表单并尝试离开当前页面时,我收到了确认提示。

现在,假设我有一个删除按钮来删除表单的资源,当删除成功时,我得到了到资源列表页面的历史记录重定向。

我的问题是:如果我开始编辑表单并最终决定点击删除按钮来删除资源而不是编辑它,历史记录会触发表单已更改,并将在历史记录重定向之前显示确认提示。

我有两个选择。首先,我可以放回初始表单状态以避免出现提示。其次,还有另一种方法可以防止在某些情况下出现提示。

最好的解决方案是什么?如果是第二个,你能告诉我该怎么做吗?

方案一(首选)

在历史重定向之前重置表单:

const mapDispatchToProps = (dispatch, { user, history, t }) => ({
  deleteUser: () => new Promise((resolve, reject) => {
    dispatch(newAlertDialog(
      t('confirmDeleteUser', { user: user.name }),
      t('confirmDeleteTitle'),
      () => dispatch(requestDeleteUser(user.id, resolve, reject)),
      t('delete'),
    ))
  }).then(() => {
    // reset form to avoid prompt user confirmation
    dispatch(reset('EditUser'));
    history.push('/users');
  })
});
Run Code Online (Sandbox Code Playgroud)

lou*_*ros 1

在我的情况下,在历史重定向之前重置表单似乎是最好的解决方案:

const mapDispatchToProps = (dispatch, { user, history, t }) => ({
  deleteUser: () => new Promise((resolve, reject) => {
    dispatch(newAlertDialog(
      t('confirmDeleteUser', { user: user.name }),
      t('confirmDeleteTitle'),
      () => dispatch(requestDeleteUser(user.id, resolve, reject)),
      t('delete'),
    ))
  }).then(() => {
    // reset form to avoid prompt user confirmation
    dispatch(reset('EditUser'));
    history.push('/users');
  })
});
Run Code Online (Sandbox Code Playgroud)

由于资源将被删除,重置表单的初始值是避免弹出提示的好方法。