React-Router返回页面如何配置历史记录?

有没有人能告诉我如何回到上一页而不是特定的路线?

使用此代码时:

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);
});
558400 次浏览

我认为你只需要在你的路由器上启用BrowserHistory,就像这样初始化它:<Router history={new BrowserHistory}>

在此之前,您应该从'react-router/lib/BrowserHistory'请求BrowserHistory

我希望这能有所帮助!

更新: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);

更新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:__abc0

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

这是一个工作的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;

当然,如果没有历史记录,你可以这样做:

<button className="back" onClick={goBack}>{this.props.children}</button>


function goBack(e) {
if (/* no history */) {
e.preventDefault();
} else {
this.history.goBack();
}
}
this.context.router.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
};

ES6方法不使用混合,使用反应路由器,无状态函数。

import React from 'react'
import { browserHistory } from 'react-router'


export const Test = () => (
<div className="">
<button onClick={browserHistory.goBack}>Back</button>
</div>
)

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

this.props.history.goBack();

在React-Router v4.X中,您可以使用history.goBack,它相当于history.go(-1)

应用程序.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"));

返回.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()可以加载访问者在打开您的应用程序之前访问过的页面。


为了防止出现上述情况,我创建了一个简单的库反应路由器最后位置,它可以监视用户的最后位置。

用法非常简单。 首先,需要从npm安装react-router-domreact-router-last-location

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

然后使用以下LastLocationProvider

应用程序.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"));

返回.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

像这样调用以下组件:

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

下面是组件:

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

我正在使用:

"react": "15.6.1"
"react-router": "4.2.0"
import { withRouter } from 'react-router-dom'


this.props.history.goBack();

我正在使用这些版本

"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
  1. 导入withRouter

    import { withRouter } from 'react-router-dom';
    
  2. Export your component as:

    export withRouter(nameofcomponent)
    
  3. Example, on button click, call goBack:

    <button onClick={this.props.history.goBack}>Back</button>
    

Tested on react-router-dom v4.3

Redux

您还可以使用react-router-redux,它具有goBack()push()

这里是一个采样包:

在应用程序的入口点,您需要ConnectedRouter,并且有时需要巧妙地连接history对象。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'),
)

我将向您展示一种连接history的方法。请注意,历史记录是如何导入到存储中的,以及如何作为单例导出,以便可以在应用程序的入口点中使用:

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

上面的示例块显示了如何加载完成设置过程的react-router-redux中间件帮助程序。

我认为接下来的部分完全是额外的,但我会把它包括在内,以防将来有人发现好处:

import { combineReducers } from 'redux'
import { routerReducer as routing } from 'react-router-redux'


export default combineReducers({
routing, form,
})

我一直使用routerReducer,因为它允许我强制重新加载通常由于shouldComponentUpdate而不会重新加载的组件。最明显的例子是,当用户按下NavLink按钮时,导航栏应该进行更新。如果您沿着这条路走下去,您将了解到Redux的Connect方法使用shouldComponentUpdate。使用routerReducer,您可以使用mapStateToProps将路由更改映射到导航栏,这将在历史记录对象更改时触发其更新。

像这样:

const mapStateToProps = ({ routing }) => ({ routing })


export default connect(mapStateToProps)(Nav)

原谅我,我为人们添加了一些额外的关键字:如果您的组件没有正确更新,请通过删除连接功能来调查shouldComponentUpdate,看看它是否解决了这个问题。如果是这样,请拉入routerReducer,该组件将在URL更改时正确更新。

最后,在完成所有这些之后,您可以随时调用goBack()push()

现在在一些随机组件中尝试它:

  1. connect()导入
  2. 您甚至不需要mapStateToPropsmapDispatchToProps
  3. 在GoBack中导入并从react-router-redux推送
  4. 调用this.props.dispatch(goBack())
  5. 调用this.props.dispatch(push('/sandwich'))
  6. 体验积极情绪

如果您需要更多采样,请查看:https://www.npmjs.com/package/react-router-redux

像这样简单地使用

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

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

this.context.router.history.goBack()

对我有用的是在我的文件的顶部导入WiThRouter.

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

然后使用它来包装我的文件底部的导出函数。

export default withRouter(WebSitePageTitleComponent)

然后允许我访问路由器的历史记录属性。下面是完整的示例代码!

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)

使用React钩子

导入:

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

在无状态组件中:

let history = useHistory();

调用事件:

history.goBack()

在事件按钮中使用的示例:

<button onClick={history.goBack}>Back</button>

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

对我来说唯一有效的解决方案是最简单的。无需额外进口。

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

谢谢,亚姆侯赛因

根据https://reacttraining.com/react-router/web/api/history

对于"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,
};

返回特定页面

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


const history = useHistory();
  

const routeChange = () => {
let path = '/login';
history.push(path);
};

返回前面的页面:

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


const history = useHistory();
  

const routeChange = () => {
history.goBack()
};

React路由器V6

useNavigate挂接是现在返回的推荐方法:

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

CodesandBox示例

后退/前进多个历史堆栈条目:
<button onClick={() => navigate(-2)}>go two back</button>
<button onClick={() => navigate(2)}>go two forward</button>
前往特定路线:
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替换useHistory支持即将到来的反应暂停/并发模式更好。

React路由器使用HTML5历史API,它建立在浏览器历史API的基础上,提供了一个我们可以在React应用程序中轻松使用的接口。历史API。所以没有导入任何东西(使用历史等)

对于功能组件:

<button onClick={()=>{ window.history.back() }}> Back </button>

对于类组件:

<button onClick={()=>{ this.window.history.back() }}> Back </button>

第1步

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

第2步

let history = useHistory();

第3步

const goToPreviousPath = (e) => {
e.preventDefault();
history.goBack()
}

第4步

<Button
onClick={goToPreviousPath}
>
Back
</Button>

react-router-dom V6

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


function goBack() {
const navigate = useNavigate();


return <button onClick={() => navigate(-1)}>go back</button>
}

我想更新一下之前的答案。 如果使用react-router >v6.0,则useHistory()不是返回的正确方法。你会得到一个错误,因为我猜useHistory()是不存在的最新版本。 这是最新的答案。

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

使用此useNavigate()挂钩。 你可以在这里阅读从v5v6的转变的官方文件。 https://reactrouter.com/docs/en/v6/upgrading/v5

在react-router V6中,当您想返回上一页时,可以使用__abc0:

步骤1:

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

步骤2:

const navigate = useNavigate();

步骤3:如果要返回上一页,请使用navigate(-1)

<button onClick={() => navigate(-1)}> Back </button>

如果您在应用程序中使用React-Native Drawer导航作为主路由器,并且希望控制后退按钮行为并返回历史记录,则可以使用来控制后退按钮。

  <NavigationContainer>
<Drawer.Navigator
backBehavior="history">
// your screens come here
</Drawer.Navigator>
</NavigationContainer>