react-router go back a page how do you configure history?

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

Can anyone please tell me how I can go back to previous page rather than a specific route?

When using this code:

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

Get this error, goBack() was ignored because there is no router history

Here are my routes:

// 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); }); 

回答1:

I think you just need to enable BrowserHistory on your router by intializing it like that : <Router history={new BrowserHistory}>.

Before that, you should require BrowserHistory from 'react-router/lib/BrowserHistory'

I hope that helps !

UPDATE : example in ES6

var BrowserHistory = require('react-router/lib/BrowserHistory').default;  var App = React.createClass({     render: function() {         return (             <div><button onClick={BrowserHistory.goBack}>Go Back</button></div>         );     } });  React.render((     <Router history={BrowserHistory}>         <Route path="/" component={App} />     </Router> ), document.body); 


回答2:

Update with React v16 and ReactRouter v4.2.0 (October 2017):

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>     )   } } 

Update with React v15 and ReactRouter v3.0.0 (August 2016):

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

Created a fiddle with a little bit more complex example with an embedded iframe: https://jsfiddle.net/kwg1da3a/

React v14 and ReacRouter v1.0.0 (Sep 10, 2015)

You can do this:

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);     }   },   ... 

You need to be careful that you have the necessary history to go back. If you hit the page directly and then hit back it will take you back in the browser history before your app.

This solution will take care of both scenarios. It will, however, not handle an iframe that can navigate within the page (and add to the browser history), with the back button. Frankly, I think that is a bug in the react-router. Issue created here: https://github.com/rackt/react-router/issues/1874



回答3:

this.context.router.goBack() 

No navigation mixin required!



回答4:

ES6 method without mixins using react-router, stateless function.

import React from 'react' import { browserHistory } from 'react-router'  export const Test = () => (   <div className="">     <button onClick={browserHistory.goBack}>Back</button>   </div> ) 


回答5:

This is a working BackButton component (React 0.14):

var React = require('react'); var Router = require('react-router');  var History = Router.History;  var BackButton = React.createClass({   mixins: [ History ],   render: function() {     return (       <button className="back" onClick={this.history.goBack}>{this.props.children}</button>     );   } });  module.exports = BackButton; 

You can off course do something like this if there is no history:

<button className="back" onClick={goBack}>{this.props.children}</button>  function goBack(e) {   if (/* no history */) {     e.preventDefault();   } else {     this.history.goBack();   } } 


回答6:

For react-router v2.x this has changed. Here's what I'm doing for ES6:

import React from 'react'; import FontAwesome from 'react-fontawesome'; import { Router, RouterContext, Link, browserHistory } from 'react-router';  export default class Header extends React.Component {    render() {     return (       <div id="header">         <div className="header-left">           {             this.props.hasBackButton &&             <FontAwesome name="angle-left" className="back-button" onClick={this.context.router.goBack} />           }         </div>         <div>{this.props.title}</div>       </div>     )   } }  Header.contextTypes = {   router: React.PropTypes.object };  Header.defaultProps = {   hasBackButton: true };  Header.propTypes = {   title: React.PropTypes.string }; 


回答7:

i) import withrouter from react-router-dom

import { withRouter } from 'react-router-dom'; 

ii) Make a function like below

goBack = (props) => {   this.props.history.goBack(); } 

iii) On button click called that function

<button onClick={this.goBack.bind(this)} >Back</button> 

iv) Export your component as

export withRouter(nameofcomponent)  


回答8:

this.props.history.goBack();

This works with Browser and Hash history.



回答9:

In react-router v4.x you can use history.goBack which is equivalent to 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); 

Demo: https://codesandbox.io/s/ywmvp95wpj

Please remember that by using history your users can leave because history.goBack() can load a page that visitor has visited before opening your application.


To prevent such situation as described above, I've created a simple library react-router-last-location that watch your users last location.

Usage is very straight forward. First you need to install react-router-dom and react-router-last-location from npm.

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

Then use LastLocationProvider as below:

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); 

Demo: https://codesandbox.io/s/727nqm99jj



回答10:

Call the following component like so:

<BackButton history={this.props.history} /> 

And here is the component:

import React, { Component } from 'react' import PropTypes from 'prop-types' class BackButton extends Component {   constructor() {     super(...arguments)      this.goBack = this.goBack.bind(this)   }    render() {     return (       <button         onClick={this.goBack}>           Back       </button>     )   }    goBack() {     this.props.history.goBack()   } }  BackButton.propTypes = {   history: PropTypes.object, }  export default BackButton 

I'm using:

"react": "15.6.1" "react-router": "4.2.0" 


回答11:

import { withRouter } from 'react-router-dom'  this.props.history.goBack(); 

I am using these versions

"react": "^15.6.1", "react-dom": "^15.6.1", "react-router": "^4.2.0", "react-router-dom": "^4.2.2", 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!