简体   繁体   English

React onbeforeunload - 不确定如何使用

[英]React onbeforeunload - not sure how to use

If a state variable called someVar is true, then when user leaves page (refresh, back, [x] button on window/tab), they get a message.如果名为someVar的 state 变量为真,则当用户离开页面(刷新、后退、窗口/选项卡上的 [x] 按钮)时,他们会收到一条消息。 On the message, if they select Cancel, they stay on page.在消息中,如果他们 select 取消,他们将留在页面上。 If they leave page, call a function (in this example, call doSomething() ).如果他们离开页面,请拨打 function(在此示例中,请拨打doSomething() )。

Note : I would like to use a class component, not functional component.注意:我想使用 class 组件,而不是功能组件。

I have some code here with some parts being pseudocode.我这里有一些代码,有些部分是伪代码。 I also have a CodeSandbox that is identical to what you see below.我还有一个与您在下面看到的相同的CodeSandbox

import React from 'react';
import {Button} from 'react-bootstrap';

class Sample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      someVar: false
    }
  }

  componentDidMount() {
    window.addEventListener("beforeunload", this.handleUnload);
    return () => {
      window.removeEventListener("beforeunload", this.handleUnload);
    }
  }

  handleUnload = (e) => {
    e.preventDefault();
    if(this.state.someVar) {
        // then show custom modal
    } else {
        // don't show custom modal
    }
  }

  handleAlert = () => {
    if(yes) {
       doSomething();
    }
    if(no) {
       // nothing. stay on page
    }

  doSomething = () => {
      //call some functions
  }

  render() {
    return (
      <h2 onClick={() => { this.setState({ someVar: true }) }} >
        ClickMe
      </h2>
   );
  }
}

You don't need to use onbeforeunload .您不需要使用onbeforeunload IMO it's enough to use componentWillUnmount life cycle as you're already using Class component. IMO 使用componentWillUnmount 生命周期就足够了,因为您已经在使用 Class 组件。

 import React from 'react'; import {Button} from 'react-bootstrap'; class Sample extends React.Component { // fix this life cycle componentWillUnmount() { this.handleUnload(); } handleUnload = (e) => { e.preventDefault(); if(this.state.someVar) { // then show custom modal } else { // don't show custom modal } } // the rest of the code.... }

You can solve it this way as well.你也可以这样解决。

  componentDidMount() {
    window.addEventListener('beforeunload', this.unload);
  }

  componentWillUnmount() {
    window.removeEventListener('beforeunload', this.unload);
  }

Just what not to use HOC:-)什么不能使用 HOC :-)

useEffect(() => {
window.onbeforeunload = () => '';
return () => {
  window.onbeforeunload = null;
};}, []);

I did a same function. Hope It will help you我做了同样的 function。希望它能帮助你

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

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