【问题标题】:Listen to page refresh and window close on react-router在 react-router 上收听页面刷新和窗口关闭
【发布时间】:2018-03-19 12:49:17
【问题描述】:

似乎react-router 中的<Prompt> 组件只监听history.block,它只在URL 更改时起作用。

我想在用户刷新 (F5) 或关闭窗口时显示相同的 <Prompt> 组件。我该怎么做?

【问题讨论】:

    标签: reactjs location react-router refresh history


    【解决方案1】:

    这是防止通过 JS 刷新页面的方法:

    PromptComponent extends Component {      
    
      // Add a listener to prevent browser page refresh
      componentWillMount() {
        onbeforeunload = e => "Don't leave"
      }
    
      // Clear listener
      componentWillUnmount() {
        onbeforeunload = null
      }
    }
    

    在这里查看:ONLINE

    【讨论】:

    • 感谢您的回答,我不想只检测用户何时刷新或离开页面,而是在发生这种情况时显示<Prompt> 组件。
    【解决方案2】:

    我知道这是旧的,但它似乎仍然有一些流量

      getSnapshotBeforeUpdate() {
        if (this.navigationPrompt()) {
          window.onbeforeunload = () => true
        } else {
          window.onbeforeunload = null
        }
        return null
      }
    
      componentWillUnmount() {
        onbeforeunload = null
      }
    

    到目前为止是我的解决方案,但它显示为默认警告 - 如果我知道如何显示我的提示,我会更新

    注意:

    this.navigationPrompt() 与我在提示中使用的逻辑控制器相同:

      <Prompt
        when={this.navigationPrompt()}
        message="It looks like you haven't sent your email, are you sure you want to leave?"
      />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-28
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多