[英]react-router go back a page how do you configure history?
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);
});
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>
)
}
}
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/
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.但是,它不会处理可以使用后退按钮在页面内导航(并添加到浏览器历史记录)的 iframe。 Frankly, I think that is a bug in the react-router.坦率地说,我认为这是反应路由器中的一个错误。 Issue created here: https://github.com/rackt/react-router/issues/1874问题在这里创建: https : //github.com/rackt/react-router/issues/1874
Using React Hooks使用 React 钩子
Import:进口:
import { useHistory } from "react-router-dom";
In stateless component:在无状态组件中:
let history = useHistory();
Call the Event:调用事件:
history.goBack()
Examples do use in event Button:在事件按钮中使用的示例:
<button onClick={history.goBack}>Back</button>
or或者
<button onClick={() => history.goBack()}>Back</button>
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);
import withRouter
用withRouter
导入
import { withRouter } from 'react-router-dom';
Export your component as:将您的组件导出为:
export withRouter(nameofcomponent)
Example, on button click, call goBack
:例如,单击按钮时,调用goBack
:
<button onClick={this.props.history.goBack}>Back</button>
Tested on react-router-dom
v4.3在react-router-dom
v4.3 上测试
this.context.router.goBack()
无需导航混合!
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>
)
Go back to specific page :返回特定页面:
import { useHistory } from "react-router-dom";
const history = useHistory();
const routeChange = () => {
let path = '/login';
history.push(path);
};
Go back to previous page:返回上一页:
import { useHistory } from "react-router-dom";
const history = useHistory();
const routeChange = () => {
history.goBack()
};
这适用于浏览器和哈希历史记录。
this.props.history.goBack();
Check out my working example using React 16.0 with React-router v4.查看我使用 React 16.0 和 React-router v4 的工作示例。 check out the code Github查看代码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
ps sorry the code is to big to post it all here ps 抱歉,代码太大了,无法将其全部发布在这里
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();
}
}
For react-router v2.x this has changed.对于 react-router v2.x,这已经改变了。 Here's what I'm doing for ES6:这是我为 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
};
In react-router v4.x you can use history.goBack
which is equivalent to history.go(-1)
.在 react-router v4.x 中,您可以使用history.goBack
,它相当于history.go(-1)
。
App.js应用程序.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返回.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演示: 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.请记住,通过使用history
您的用户可以离开,因为history.goBack()
可以在打开您的应用程序之前加载访问者访问过的页面。
To prevent such situation as described above, I've created a simple library react-router-last-location that watch your users last location.为了防止上述情况,我创建了一个简单的库react-router-last-location来监视用户的最后位置。
Usage is very straight forward.使用非常简单。 First you need to install react-router-dom
and react-router-last-location
from npm
.首先,您需要从npm
安装react-router-dom
和react-router-last-location
。
npm install react-router-dom react-router-last-location --save
Then use LastLocationProvider
as below:然后使用LastLocationProvider
如下:
App.js应用程序.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返回.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演示: https : //codesandbox.io/s/727nqm99jj
useNavigate
Hook is the recommended way to go back now: useNavigate
Hook 是现在返回的推荐方式:
import { useNavigate } from 'react-router-dom';
function App() {
const navigate = useNavigate();
return (
<>
<button onClick={() => navigate(-1)}>go back</button>
<button onClick={() => navigate(1)}>go forward</button>
</>
);
}
Go back/forward multiple history stack entries:
后退/前进多个历史堆栈条目:
<button onClick={() => navigate(-2)}>go two back</button> <button onClick={() => navigate(2)}>go two forward</button>
Go to specific route:
前往具体路线:
navigate("users") // go to users route, like history.push navigate("users", { replace: true }) // go to users route, like history.replace navigate("users", { state }) // go to users route, pass some state in
useNavigate
replaces useHistory
to support upcoming React Suspense/Concurrent mode better. useNavigate
替换了useHistory
以更好地支持即将到来的 React Suspense/Concurrent 模式。
What worked for me was to import withRouter at the top of my file;对我有用的是在我的文件顶部导入 withRouter ;
import { withRouter } from 'react-router-dom'
Then use it to wrap the exported function at the bottom of my file;然后用它把导出的函数包装在我的文件底部;
export default withRouter(WebSitePageTitleComponent)
Which then allowed me to access the Router's history prop.然后允许我访问路由器的历史记录道具。 Full sample code below!完整示例代码如下!
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
class TestComponent extends Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
event.preventDefault()
this.props.history.goBack()
}
render() {
return (
<div className="page-title">
<a className="container" href="/location" onClick={this.handleClick}>
<h1 className="page-header">
{ this.props.title }
</h1>
</a>
</div>
)
}
}
const { string, object } = PropTypes
TestComponent.propTypes = {
title: string.isRequired,
history: object
}
export default withRouter(TestComponent)
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",
REDUX还原
You can also use react-router-redux
which has goBack()
and push()
.您还可以使用具有goBack()
和push()
react-router-redux
。
Here is a sampler pack for that:这是一个示例包:
In your app's entry point, you need ConnectedRouter
, and a sometimes tricky connection to hook up is the history
object.在您的应用程序的入口点中,您需要ConnectedRouter
,而有时需要ConnectedRouter
棘手连接是history
对象。 The Redux middleware listens to history changes: Redux 中间件监听历史变化:
import React from 'react'
import { render } from 'react-dom'
import { ApolloProvider } from 'react-apollo'
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'react-router-redux'
import client from './components/apolloClient'
import store, { history } from './store'
import Routes from './Routes'
import './index.css'
render(
<ApolloProvider client={client}>
<Provider store={store}>
<ConnectedRouter history={history}>
<Routes />
</ConnectedRouter>
</Provider>
</ApolloProvider>,
document.getElementById('root'),
)
I will show you a way to hook up the history
.我将向您展示一种连接history
。 Notice how the history is imported into the store and also exported as a singleton so it can be used in the app's entry point:请注意历史记录是如何导入到商店中并作为单例导出的,以便它可以在应用程序的入口点中使用:
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory'
import rootReducer from './reducers'
export const history = createHistory()
const initialState = {}
const enhancers = []
const middleware = [thunk, routerMiddleware(history)]
if (process.env.NODE_ENV === 'development') {
const { devToolsExtension } = window
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension())
}
}
const composedEnhancers = compose(applyMiddleware(...middleware), ...enhancers)
const store = createStore(rootReducer, initialState, composedEnhancers)
export default store
The above example block shows how to load the react-router-redux
middleware helpers which complete the setup process.上面的示例块显示了如何加载完成设置过程的react-router-redux
中间件助手。
I think this next part is completely extra, but I will include it just in case someone in the future finds benefit:我认为下一部分完全是额外的,但我会包括它,以防将来有人发现好处:
import { combineReducers } from 'redux'
import { routerReducer as routing } from 'react-router-redux'
export default combineReducers({
routing, form,
})
I use routerReducer
all the time because it allows me to force reload Components that normally do not due to shouldComponentUpdate
.我一直使用routerReducer
因为它允许我强制重新加载通常不会由于shouldComponentUpdate
引起的shouldComponentUpdate
。 The obvious example is when you have a Nav Bar that is supposed to update when a user presses a NavLink
button.一个明显的例子是当你有一个导航栏,当用户按下一个NavLink
按钮时它应该更新。 If you go down that road, you will learn that Redux's connect method uses shouldComponentUpdate
.如果你沿着这条路走下去,你会了解到 Redux 的 connect 方法使用shouldComponentUpdate
。 With routerReducer
, you can use mapStateToProps
to map routing changes into the Nav Bar, and this will trigger it to update when the history object changes.使用routerReducer
,您可以使用mapStateToProps
将路由更改映射到导航栏,这将在历史对象更改时触发它更新。
Like this:像这样:
const mapStateToProps = ({ routing }) => ({ routing })
export default connect(mapStateToProps)(Nav)
Forgive me while I add some extra keywords for people: if your component isn't updating properly, investigate shouldComponentUpdate
by removing the connect function and see if it fixes the problem.请原谅我为人们添加了一些额外的关键字:如果您的组件没有正确更新, shouldComponentUpdate
通过删除连接功能来调查shouldComponentUpdate
并查看它是否解决了问题。 If so, pull in the routerReducer
and the component will update properly when the URL changes.如果是这样,拉入routerReducer
,组件会在 URL 更改时正确更新。
In closing, after doing all that, you can call goBack()
or push()
anytime you want!最后,完成所有这些之后,您可以随时调用goBack()
或push()
!
Try it now in some random component:现在在一些随机组件中尝试:
connect()
在connect()
导入mapStateToProps
or mapDispatchToProps
你甚至不需要mapStateToProps
或mapDispatchToProps
react-router-redux
导入 goBack 并从react-router-redux
推送this.props.dispatch(goBack())
调用this.props.dispatch(goBack())
this.props.dispatch(push('/sandwich'))
调用this.props.dispatch(push('/sandwich'))
If you need more sampling, check out: https://www.npmjs.com/package/react-router-redux如果您需要更多采样,请查看: https : //www.npmjs.com/package/react-router-redux
The only solution that worked for me was the most simple.唯一对我有用的解决方案是最简单的。 No additional imports needed.不需要额外的进口。
<a href="#" onClick={() => this.props.history.goBack()}>Back</a>
Tks, IamMHussain Tks, IamMHussain
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"
只需像这样使用
<span onClick={() => this.props.history.goBack()}>Back</span>
React Router uses the HTML5 History API, which builds on the browser history API to provide an interface to which we can use easily in React apps. React Router 使用 HTML5 History API,它建立在浏览器历史 API 之上,提供了一个我们可以在 React 应用程序中轻松使用的界面。History API .历史 API 。 So without import anything (useHistory, etc)因此无需导入任何内容(useHistory 等)
for functional component:对于功能组件:
<button onClick={()=>{ window.history.back() }}> Back </button>
for class component:对于类组件:
<button onClick={()=>{ this.window.history.back() }}> Back </button>
If you are using react-router v6, when you want to go back to the previous page you can do that with the Link
:如果你使用的是 react-router v6,当你想返回上一页时,你可以使用Link
来实现:
Step 1: you need to import Link
from react-router-dom
第 1 步:您需要从react-router-dom
导入Link
import { Link } from 'react-router-dom';
Step 2: wrap up the button with Link
like this.第 2 步:像这样用Link
包裹按钮。 It works perfectly.它工作得很好。
<Link to='..'>
<Button type='button'>Go Back</Button>
</Link>
这段代码将为您解决问题。
this.context.router.history.goBack()
Step-1第1步
import { useHistory } from "react-router-dom";`
Step-2第2步
let history = useHistory();
Step-3步骤 3
const goToPreviousPath = (e) => {
e.preventDefault();
history.goBack()
}
step-4第四步
<Button
onClick={goToPreviousPath}
>
Back
</Button>
react-router-dom
v6在react-router-dom
v6 上import { useNavigate } from 'react-router-dom';
function goBack() {
const navigate = useNavigate();
return <button onClick={() => navigate(-1)}>go back</button>
}
I want to update the previous answers a bit.我想稍微更新一下以前的答案。 If you are using react-router >v6.0<\/code> then the
useHistory()<\/code> is not the right way to go back.
如果您使用的是
react-router >v6.0<\/code> ,那么
useHistory()<\/code>不是返回的正确方法。
You will get an error as I guess
useHistory()<\/code> is not present in the latest version.
你会得到一个错误,因为我猜
useHistory()<\/code>在最新版本中不存在。
So this is the updated answer所以这是更新的答案
// This is a React Router v6 app
import { useNavigate } from "react-router-dom";
function App() {
const navigate = useNavigate();
return (
<>
<button onClick={() => navigate(-2)}>
Go 2 pages back
</button>
<button onClick={() => navigate(-1)}>Go back</button>
<button onClick={() => navigate(1)}>
Go forward
</button>
<button onClick={() => navigate(2)}>
Go 2 pages forward
</button>
</>
);
}
in react-router v6 when you want go back to last page you should use of (navigate)在 react-router v6 中,当您想要 go 回到最后一页时,您应该使用(导航)
for example: step 1:例如:第 1 步:
import { useNavigate } from "react-router-dom";
step2:第2步:
const navigate = useNavigate();
step 3: if you want go back to last page use this:第 3 步:如果您希望 go 返回最后一页,请使用:
<button onClick={() => navigate(-1)}> back </button>
if you are using react-native drawer navigation as main router in your application and want to control back button behavior and go back historically you can use to control back button.如果您在应用程序中使用 react-native drawer navigation 作为主路由器,并且想要控制后退按钮行为并返回历史记录,您可以使用它来控制后退按钮。
<NavigationContainer> <Drawer.Navigator backBehavior="history"> // your screens come here </Drawer.Navigator> </NavigationContainer>
According to https://reacttraining.com/react-router/web/api/history根据https://reacttraining.com/react-router/web/api/history
For "react-router-dom": "^5.1.2",
,对于"react-router-dom": "^5.1.2",
,
const { history } = this.props;
<Button onClick={history.goBack}>
Back
</Button>
YourComponent.propTypes = {
history: PropTypes.shape({
goBack: PropTypes.func.isRequired,
}).isRequired,
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.