繁体   English   中英

React&MobX-用户离开现有页面时的“确认”对话框

[英]React & MobX - Confirmation dialog when a user navigates away from the existing page

我有这样的东西:

import React from 'react';
import PropTypes from 'prop-types';
import { Prompt } from 'react-router-dom';

const ConfirmationDialog = (props) => {
  if (props.navigatingAway) {
    window.onbeforeunload = () => true;
  } else {
    window.onbeforeunload = null;
  }
  return (
    <Prompt
      when={props.navigatingAway}
      message="Are you sure?"
    />
  );
};

ConfirmationDialog.propTypes = {
  navigatingAway: PropTypes.bool.isRequired,
};

export default ConfirmationDialog;

我正在尝试找出扩展此方法的最佳方法,以便navigatingAway实际上可以执行某些操作。 我不知道要使用什么标准,只是在以下情况下它应该触发确认窗口:

  • 用户更改URL并尝试导航
  • 用户点击链接
  • 用户刷新浏览器

什么when检查URL更改的最佳方法是when

当一种情况发生时,您无需想出一种“检测”方法。

  • 用户更改URL并尝试导航
  • 用户刷新浏览器

这些已经通过将回调分配给onbeforeunload

  • 用户点击链接

如果您正在使用react-router处理导航,则已经通过呈现Prompt来处理此问题。

props.navigatingAway的话,会得到更好的命名props.shouldPreventNavigation或类似的规定,因为其应,如果你要防止浏览,你不是是否进行导航。

例如,如果您始终希望在安装ConfirmationDialog同时在导航之前出现提示,则props.shouldPreventNavigation应该始终为true,就可以完成了。 一个常见的用例是,如果表单中有未保存的数据,则将其设置为true。

Prompt的文档中:

您可以始终渲染它,而可以通过when={true}when={false}来阻止或允许进行相应的导航,而不是有条件地在防护罩后面渲染<Prompt>

为了说明这一点,除了性能等方面,以下两个片段在功能上是等效的:

render() {
    return (
        <Prompt
            when={this.props.navigatingAway}
            message="Are you sure?"
        />
    )
}
render() {
    if (this.props.navigatingAway) {
        return (
            <Prompt
                when={true}
                message="Are you sure?"
            />
        )
    }
    return null;
}

如果在when={true} Prompt无法立即正常使用,则可能是您的路由未由react-router正确管理。

附带说明一下,请确保您考虑了window.onbeforeunload情况,例如,如果在为ConfirmationDialog分配了回调时将其卸载,则该操作会发生。 使用适当的生命周期方法进行管理,否则在进行测试时会变得很奇怪。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM