使用React-Router检测用户离开页面

reactjs React.js

飞云LEY

2020-03-12

我希望我的ReactJS应用在离开特定页面时通知用户。特别是一条弹出消息,提醒他/她进行以下操作:

“更改已保存,但尚未发布。现在执行吗?”

我应该在react-router全局范围内触发此操作,还是可以在react页面/组件内完成此操作?

我还没有发现任何关于后者的信息,我宁愿避免使用第一个。除非当然是它的规范,否则这使我想知道如何执行这样的事情而不必向用户可以访问的所有其他可能的页面添加代码。

欢迎有任何见解,谢谢!

第1222篇《使用React-Router检测用户离开页面》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
Green逆天 2020.03.12

使用history.listen

例如下面的例子:

在您的组件中

componentWillMount() {
    this.props.history.listen(() => {
      // Detecting, user has changed URL
      console.info(this.props.history.location.pathname);
    });
}
梅路易 2020.03.12

您可以使用此提示。

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Prompt } from "react-router-dom";

function PreventingTransitionsExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Form</Link>
          </li>
          <li>
            <Link to="/one">One</Link>
          </li>
          <li>
            <Link to="/two">Two</Link>
          </li>
        </ul>
        <Route path="/" exact component={Form} />
        <Route path="/one" render={() => <h3>One</h3>} />
        <Route path="/two" render={() => <h3>Two</h3>} />
      </div>
    </Router>
  );
}

class Form extends Component {
  state = { isBlocking: false };

  render() {
    let { isBlocking } = this.state;

    return (
      <form
        onSubmit={event => {
          event.preventDefault();
          event.target.reset();
          this.setState({
            isBlocking: false
          });
        }}
      >
        <Prompt
          when={isBlocking}
          message={location =>
            `Are you sure you want to go to ${location.pathname}`
          }
        />

        <p>
          Blocking?{" "}
          {isBlocking ? "Yes, click a link or the back button" : "Nope"}
        </p>

        <p>
          <input
            size="50"
            placeholder="type something to block transitions"
            onChange={event => {
              this.setState({
                isBlocking: event.target.value.length > 0
              });
            }}
          />
        </p>

        <p>
          <button>Submit to stop blocking</button>
        </p>
      </form>
    );
  }
}

export default PreventingTransitionsExample;

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android