react-router返回页面如何配置历史记录?

JavaScript

十三神无

2020-03-12

谁能告诉我如何返回上一页而不是特定路线?

使用此代码时:

var BackButton = React.createClass({

 mixins: [Router.Navigation],
  render: function() {
    return (
        <button
            className="button icon-left"
            onClick={this.navigateBack}>
            Back
        </button>
    );
  },

  navigateBack: function(){
    this.goBack();
  }
});

收到此错误,因为没有路由器历史记录所以goBack()被忽略了

这是我的路线:

// Routing Components
Route = Router.Route;
RouteHandler = Router.RouteHandler;
DefaultRoute = Router.DefaultRoute;

var routes = (
 <Route name="app" path="/" handler={OurSchoolsApp}>
     <DefaultRoute name="home" handler={HomePage} />
     <Route name="add-school" handler={AddSchoolPage}  />
     <Route name="calendar" handler={CalendarPage}  />
     <Route name="calendar-detail" path="calendar-detail/:id" handler={CalendarDetailPage} />
     <Route name="info-detail" path="info-detail/:id" handler={InfoDetailPage} />
     <Route name="info" handler={InfoPage} />
     <Route name="news" handler={NewsListPage} />
     <Route name="news-detail" path="news-detail/:id" handler={NewsDetailPage} />
     <Route name="contacts" handler={ContactPage} />
     <Route name="contact-detail" handler={ContactDetailPage} />
     <Route name="settings" handler={SettingsPage} />
 </Route>
 );

 Router.run(routes, function(Handler){
   var mountNode = document.getElementById('app');
   React.render(<Handler /> , mountNode);
 });

第959篇《react-router返回页面如何配置历史记录?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

8个回答
Pro神无猴子 2020.03.12

这段代码将为您解决问题。

this.context.router.history.goBack()
阿飞路易 2020.03.12

像这样简单地使用

<span onClick={() => this.props.history.goBack()}>Back</span>
Pro凯 2020.03.12

对我有用的唯一解决方案是最简单的。无需其他进口。

<a href="#" onClick={() => this.props.history.goBack()}>Back</a>

伊姆·特克斯(Tks,Iam)

小哥斯丁 2020.03.12

使用React挂钩

进口:

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

在无状态组件中:

  let history = useHistory();

活动中

history.goBack()
ALPro 2020.03.12

在react-router v4.x中,您可以使用history.goBack等效于history.go(-1)

App.js

import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";
import Back from "./Back";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "left"
};

const App = () => (
  <div style={styles}>
    <Router>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/contact">Contact</Link></li>
        </ul>

        <hr />

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />

        <Back />{/* <----- This is component that will render Back button */}
      </div>
    </Router>
  </div>
);

render(<App />, document.getElementById("root"));

Back.js

import React from "react";
import { withRouter } from "react-router-dom";

const Back = ({ history }) => (
  <button onClick={history.goBack}>Back to previous page</button>
);

export default withRouter(Back);

演示: https //codesandbox.io/s/ywmvp95wpj

请记住,使用history用户可以离开,因为history.goBack()可以在打开您的应用程序之前加载访问者访问过的页面。


为避免上述情况,我创建了一个简单的库react-router-last-location,用于监视用户的最后位置。

用法非常简单。首先,你需要安装react-router-domreact-router-last-locationnpm

npm install react-router-dom react-router-last-location --save

然后使用LastLocationProvider如下:

App.js

import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { LastLocationProvider } from "react-router-last-location";
//              ↑
//              |
//              |
//
//       Import provider
//
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";
import Back from "./Back";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "left"
};

const App = () => (
  <div style={styles}>
    <h5>Click on About to see your last location</h5>
    <Router>
      <LastLocationProvider>{/* <---- Put provider inside <Router> */}
        <div>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/contact">Contact</Link></li>
          </ul>

          <hr />

          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/contact" component={Contact} />

          <Back />
        </div>
      </LastLocationProvider>
    </Router>
  </div>
);

render(<App />, document.getElementById("root"));

Back.js

import React from "react";
import { Link } from "react-router-dom";
import { withLastLocation } from "react-router-last-location";
//              ↑
//              |
//              |
//
//    `withLastLocation` higher order component
//    will pass `lastLocation` to your component               
//
//                   |
//                   |
//                   ↓
const Back = ({ lastLocation }) => (
  lastLocation && <Link to={lastLocation || '/'}>Back to previous page</Link>
);


//          Remember to wrap
//   your component before exporting
//
//                   |
//                   |
//                   ↓
export default withLastLocation(Back);

演示: https : //codesandbox.io/s/727nqm99jj

Mandy猿 2020.03.12

这适用于浏览器和哈希历史记录。

this.props.history.goBack();
十三西里GO 2020.03.12
this.context.router.goBack()

无需导航混入!

Jim米亚西里 2020.03.12

使用React v16和ReactRouter v4.2.0更新(2017年10月):

class BackButton extends Component {
  static contextTypes = {
    router: () => true, // replace with PropTypes.object if you use them
  }

  render() {
    return (
      <button
        className="button icon-left"
        onClick={this.context.router.history.goBack}>
          Back
      </button>
    )
  }
}

使用React v15和ReactRouter v3.0.0更新(2016年8月):

var browserHistory = ReactRouter.browserHistory;

var BackButton = React.createClass({
  render: function() {
    return (
      <button
        className="button icon-left"
        onClick={browserHistory.goBack}>
        Back
      </button>
    );
  }
});

用嵌入式iframe创建了一个带有一些更复杂示例的小提琴:https//jsfiddle.net/kwg1da3a/

React v14和ReacRouter v1.0.0(2015年9月10日)

你可以这样做:

var React = require("react");
var Router = require("react-router");

var SomePage = React.createClass({
  ...

  contextTypes: {
    router: React.PropTypes.func
  },
  ...

  handleClose: function () {
    if (Router.History.length > 1) {
      // this will take you back if there is history
      Router.History.back();
    } else {
      // this will take you to the parent route if there is no history,
      // but unfortunately also add it as a new route
      var currentRoutes = this.context.router.getCurrentRoutes();
      var routeName = currentRoutes[currentRoutes.length - 2].name;
      this.context.router.transitionTo(routeName);
    }
  },
  ...

您需要小心,以确保有必要的历史记录才能返回。如果您直接点击该页面,然后再点击该页面,它将带您回到浏览器历史记录中,然后再查看您的应用。

此解决方案将同时考虑这两种情况。但是,它将无法使用后退按钮处理可在页面内导航(并添加到浏览器历史记录)的iframe。坦白说,我认为这是react-router中的错误。在此处创建的问题:https//github.com/rackt/react-router/issues/1874

问题类别

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