簡體   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