有谁能告诉我如何回到上一页而不是特定路线?
使用此代码时:
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);
});
答案 0 :(得分:38)
this.context.router.goBack()
无需导航混合!
答案 1 :(得分:34)
我认为您只需要在路由器上启用BrowserHistory,方法是将其初始化为<Router history={new BrowserHistory}>
。
在此之前,您需要BrowserHistory
'react-router/lib/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);
答案 2 :(得分:30)
使用react-router,无状态函数的没有mixins的ES6方法。
import React from 'react'
import { browserHistory } from 'react-router'
export const Test = () => (
<div className="">
<button onClick={browserHistory.goBack}>Back</button>
</div>
)
答案 3 :(得分:25)
导入withRouter
import { withRouter } from 'react-router-dom';
将您的组件导出为:
export withRouter(nameofcomponent)
示例,点击按钮时,请致电goBack
:
<button onClick={this.props.history.goBack}>Back</button>
在react-router-dom
v4.3
答案 4 :(得分:15)
返回特定页面:
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()
};
答案 5 :(得分:6)
对于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
};
答案 6 :(得分:6)
这是一个有效的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();
}
}
答案 7 :(得分:5)
使用React 16.0和React-router v4 Live Example查看我的工作示例。检出代码Github
使用withRouter
和history.goBack()
这就是我正在实施的想法...
History.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
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。抱歉,代码太大了,不能全部张贴在这里
答案 8 :(得分:3)
this.props.history.goBack();
这适用于浏览器和哈希历史记录。
答案 9 :(得分:2)
在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()
可以在打开您的应用程序之前加载访问者访问过的网页。
为了防止上述情况,我创建了一个简单的库react-router-last-location,可以观察用户的最后位置。
用法非常简单。
首先,您需要从react-router-dom
安装react-router-last-location
和npm
。
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);
答案 10 :(得分:2)
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
我正在使用这些版本
Insert into #ExpectedCombineOutput
select distinct min(startdate), max(enddate) from
(
Select tc.IdDoc as IdDoc, tcw.IdDoc as SecIdDoc,
case when (tc.startdate between tcw.startdate and tcw.enddate) then tcw.startdate else tc.StartDate end as StartDate,
case when (tc.enddate between tcw.startdate and tcw.enddate) then tcw.enddate else tc.EndDate end as EndDate
from #TableToCombine tc
left join #TableToCombine tcw on tc.IdDoc <> tcw.IdDoc
) test group by IdDoc
Insert into #ExpectedIntersectOutput
Select case when ti.startdate <= tc.startdate then tc.startdate else ti.startdate end as 'StartDate',
case when ti.enddate >= tc.enddate then tc.enddate else ti.enddate end as 'EndDate'
from #TableToIntersect ti
inner join #ExpectedCombineOutput tc on 1=1
答案 11 :(得分:2)
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>
</>
);
}
返回/转发多个历史记录堆栈条目:
<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
replaces useHistory
到support更好的即将到来的React Suspense / Concurrent模式。
答案 12 :(得分:2)
使用React挂钩
导入:
import { useHistory } from "react-router-dom";
在无状态组件中:
let history = useHistory();
活动中
history.goBack()
答案 13 :(得分:2)
对我有用的唯一解决方案是最简单的。无需其他进口。
<a href="#" onClick={() => this.props.history.goBack()}>Back</a>
Tks,IamMHussain
答案 14 :(得分:1)
如下所示调用以下组件:
<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"
答案 15 :(得分:1)
对我有用的是在文件顶部使用Router导入;
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)
答案 16 :(得分:0)
React Router 使用 HTML5 History API,它建立在浏览器历史 API 之上,提供了一个我们可以在 React 应用程序中轻松使用的界面。 History API。因此无需导入任何内容(useHistory 等)
对于功能组件:
<button onClick={()=>{ window.history.back() }}> Back </button>
对于类组件:
<button onClick={()=>{ this.window.history.back() }}> Back </button>
答案 17 :(得分:0)
`Step-1 : import { useHistory } from "react-router-dom";
Step-2 : let history = useHistory();
Step-3 : const goToPreviousPath = (e) => {
e.preventDefault();
history.goBack()
}
step-4 : <Button
onClick={goToPreviousPath}
>
Back
</Button>`
答案 18 :(得分:0)
这段代码将为您解决问题。
this.context.router.history.goBack()
答案 19 :(得分:0)
只需这样使用
<span onClick={() => this.props.history.goBack()}>Back</span>
答案 20 :(得分:0)
<强> REDUX 强>
您还可以使用react-router-redux
和goBack()
的{{1}}。
以下是一个采样器包:
在您应用的入口点,您需要push()
,并且有时棘手的连接是ConnectedRouter
对象。 Redux中间件监听历史变化:
history
我将向您展示一种挂钩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
按钮时,应该更新导航栏。如果您走这条路,您将了解Redux的连接方法使用NavLink
。使用shouldComponentUpdate
,您可以使用routerReducer
将路由更改映射到导航栏,这将触发它在历史记录对象更改时进行更新。
像这样:
mapStateToProps
请原谅我为人们添加一些额外的关键字:如果您的组件未正确更新,请通过删除connect函数调查const mapStateToProps = ({ routing }) => ({ routing })
export default connect(mapStateToProps)(Nav)
,看看它是否解决了问题。如果是这样,请拉入shouldComponentUpdate
,当网址发生变化时,组件会正确更新。
最后,完成所有操作后,您可以随时拨打routerReducer
或goBack()
!
现在在一些随机组件中尝试:
push()
connect()
或mapStateToProps
mapDispatchToProps
react-router-redux
this.props.dispatch(goBack())
如果您需要更多抽样,请查看:https://www.npmjs.com/package/react-router-redux
答案 21 :(得分:-1)
根据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,
};
答案 22 :(得分:-1)
单行答案:
myDataSet = {"some string", "some other string"}
mAdapter = new MyAdapter(myDataSet);