Javascript react-router 返回一个页面 你如何配置历史记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30915173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
react-router go back a page how do you configure history?
提问by Bomber
Can anyone please tell me how I can go back to the 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
得到这个错误,goBack() 被忽略,因为没有路由器历史记录
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);
});
采纳答案by Ghislaindj
I think you just need to enable BrowserHistory on your router by intializing it like that : <Router history={new BrowserHistory}>
.
我认为你只需要像这样初始化它就可以在你的路由器上启用 BrowserHistory : <Router history={new BrowserHistory}>
。
Before that, you should require BrowserHistory
from 'react-router/lib/BrowserHistory'
在此之前,您应该要求BrowserHistory
从'react-router/lib/BrowserHistory'
I hope that helps !
我希望有帮助!
UPDATE : example in ES6
更新:ES6 中的示例
const BrowserHistory = require('react-router/lib/BrowserHistory').default;
const App = React.createClass({
render: () => {
return (
<div><button onClick={BrowserHistory.goBack}>Go Back</button></div>
);
}
});
React.render((
<Router history={BrowserHistory}>
<Route path="/" component={App} />
</Router>
), document.body);
回答by mlunoe
Update with React v16 and ReactRouter v4.2.0 (October 2017):
更新 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>
)
}
}
Update with React v15 and ReactRouter v3.0.0 (August 2016):
更新 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>
);
}
});
Created a fiddle with a little bit more complex example with an embedded iframe: https://jsfiddle.net/kwg1da3a/
创建了一个带有嵌入式 iframe 的更复杂示例的小提琴:https: //jsfiddle.net/kwg1da3a/
React v14 and ReacRouter v1.0.0 (Sep 10, 2015)
React v14 和 ReacRouter v1.0.0(2015 年 9 月 10 日)
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
此解决方案将处理这两种情况。但是,它不会处理可以使用后退按钮在页面内导航(并添加到浏览器历史记录)的 iframe。坦率地说,我认为这是反应路由器中的一个错误。问题在这里创建:https: //github.com/rackt/react-router/issues/1874
回答by gaurav makwana
import
withRouter
import { withRouter } from 'react-router-dom';
Export your component as:
export withRouter(nameofcomponent)
Example, on button click, call
goBack
:<button onClick={this.props.history.goBack}>Back</button>
进口
withRouter
import { withRouter } from 'react-router-dom';
将您的组件导出为:
export withRouter(nameofcomponent)
例如,单击按钮时,调用
goBack
:<button onClick={this.props.history.goBack}>Back</button>
Tested on react-router-dom
v4.3
在react-router-dom
v4.3 上测试
回答by ahhhhhhhhhhhhhhhhhhhhhhhhhhhhh
this.context.router.goBack()
No navigation mixin required!
无需导航混合!
回答by ptorsson
ES6 method without mixins using react-router, stateless function.
使用 react-router 的无混合 ES6 方法,无状态功能。
import React from 'react'
import { browserHistory } from 'react-router'
export const Test = () => (
<div className="">
<button onClick={browserHistory.goBack}>Back</button>
</div>
)
回答by Eric Roberto
Using React Hooks
使用 React 钩子
Import:
进口:
import { useHistory } from "react-router-dom";
In stateless component:
在无状态组件中:
let history = useHistory();
On Event
活动现场
history.goBack()
回答by Morris S
Check out my working example using React 16.0 with React-router v4 Live Example. check out the code Github
查看我使用 React 16.0 和 React-router v4 Live Example 的工作示例。查看代码Github
Use withRouter
and history.goBack()
使用withRouter
和history.goBack()
This is the idea I am implementing...
这是我正在实施的想法......
History.js
历史.js
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'
import './App.css'
class History extends Component {
handleBack = () => {
this.props.history.goBack()
}
handleForward = () => {
console.log(this.props.history)
this.props.history.go(+1)
}
render() {
return <div className="container">
<div className="row d-flex justify-content-between">
<span onClick={this.handleBack} className="d-flex justify-content-start button">
<i className="fas fa-arrow-alt-circle-left fa-5x"></i>
</span>
<span onClick={this.handleForward} className="d-flex justify-content-end button">
<i className="fas fa-arrow-alt-circle-right fa-5x"></i>
</span>
</div>
</div>
}
}
export default withRouter(History)
PageOne.js
PageOne.js
import React, { Fragment, Component } from 'react'
class PageOne extends Component {
componentDidMount(){
if(this.props.location.state && this.props.location.state.from != '/pageone')
this.props.history.push({
pathname: '/pageone',
state: {
from: this.props.location.pathname
}
});
}
render() {
return (
<Fragment>
<div className="container-fluid">
<div className="row d-flex justify-content-center">
<h2>Page One</h2>
</div>
</div>
</Fragment>
)
}
}
export default PageOne
p.s. sorry the code is to big to post it all here
ps 抱歉,代码太大了,无法将其全部发布在这里
回答by user3322876
This works with Browser and Hash history.
这适用于浏览器和哈希历史记录。
this.props.history.goBack();
回答by ngstschr
This is a working BackButton component (React 0.14):
这是一个可用的 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;
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();
}
}
回答by aceofspades
For react-router v2.x this has changed. Here's what I'm doing for ES6:
对于 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
};