react-router回到页面如何configuration历史logging?
任何人都可以告诉我如何可以回到前一页,而不是一个特定的路线?
当使用这个代码时:
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()被忽略,因为没有路由器的历史logging
这是我的路线:
// 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); });
我想你只需要在你的路由器上启用BrowserHistory,就像这样初始化它: <Router history={new BrowserHistory}>
。
在此之前,你应该从'react-router/lib/BrowserHistory'
需要BrowserHistory
我希望有帮助!
更新:在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);
this.context.router.goBack()
不需要导航混搭!
ES6方法,无需使用反应路由器,无状态function。
import React from 'react' import { browserHistory } from 'react-router' export const Test = () => ( <div className=""> <button onClick={browserHistory.goBack}>Back</button> </div> )
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> ); } });
用embedded式iframe创build一个更复杂一点的小提琴: 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); } }, ...
你需要小心,你有必要的历史回来。 如果您直接点击该页面,然后回到页面,则会在您的应用程序之前将您带回浏览器历史logging中。
该解决scheme将处理这两种情况。 但是,它不会处理可以在页面内导航(并添加到浏览器历史logging)的后台button。 坦率地说,我认为这是反应路由器中的一个错误。 此处创build的问题: https : //github.com/rackt/react-router/issues/1874
这是一个工作的BackButton组件(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;
如果没有历史logging,你可以从这里做这样的事情:
<button className="back" onClick={goBack}>{this.props.children}</button> function goBack(e) { if (/* no history */) { e.preventDefault(); } else { this.history.goBack(); } }
对于react-router v2.x,这已经改变了。 以下是我正在为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 };
在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()
可以加载访问者在打开您的应用程序之前访问过的页面。
为了防止上述情况发生,我创build了一个简单的库react-router-last-location来监视用户的最后位置。
用法非常简单。 首先你需要从npm
安装react-router-dom
和react-router-last-location
。
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
this.props.history.goBack();
这适用于浏览器和哈希历史logging。