谁能告诉我如何返回上一页而不是特定路径?
使用此代码时:
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);
});
最佳答案
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 的更复杂示例的 fiddle :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);
}
},
...
你需要小心,你有必要的历史可以回去。如果您直接点击该页面然后返回,它会将您带回到您的应用程序之前的浏览器历史记录中。
此解决方案将处理这两种情况。但是,它不会处理可以使用后退按钮在页面内导航(并添加到浏览器历史记录)的 iframe。坦率地说,我认为这是 react-router 中的一个错误。此处创建的问题:https://github.com/rackt/react-router/issues/1874
关于javascript - react-router 返回一个页面 你如何配置历史记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30915173/