首页 > 解决方案 > 如何禁用 React Router 中的后退按钮?

问题描述

我试图禁用浏览器中的后退按钮,但它只是将页面重新加载到 path="/"

如何禁用浏览器的后退按钮,所以当用户单击它时没有任何反应?

export default class Main extends Component {
  componentDidMount() {
    const history = createBrowserHistory();
    history.listen((newLocation, action) => {
      if (action === "POP") {
        history.go(0);
      }
    });
  }
  render() {
    return (
      <div>
        <Router>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/main/component1" component={Component1} />
            <Route path="/main/component2" component={Component2} />
            <Route path="/main/component3" component={Component3} />
          </Switch>
        </Router>
      </div>
    );
  }
}

标签: reactjsreact-router

解决方案


您可以使用 react-router-dom 来完成

import { useHistory } from "react-router-dom";

let history = useHistory();
history.replace("/login");

推荐阅读