Javascript react-router (v4) 怎么回去?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46681387/
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 (v4) how to go back?
提问by Akshay Lokur
Trying to figure out how can I go back to the previous page. I am using [react-router-v4][1]
试图弄清楚我怎样才能回到上一页。我在用[react-router-v4][1]
This is the code I have configured in my first landing page:
这是我在第一个登陆页面中配置的代码:
<Router>
<div>
<Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
<Route exact path="/" component={Page1}/>
<Route path="/Page2" component={Page2}/>
<Route path="/Page3" component={Page3}/>
</div>
</Router>
In order to forward to subsequent pages, I simply do:
为了转发到后续页面,我只是这样做:
this.props.history.push('/Page2');
However, how can I go back to previous page?
Tried few things like mentioned below but no luck:
1. this.props.history.goBack();
但是,我怎样才能回到上一页?尝试了下面提到的几件事,但没有运气:1。this.props.history.goBack();
Gives error:
给出错误:
TypeError: null is not an object (evaluating 'this.props')
类型错误:null 不是对象(评估“this.props”)
this.context.router.goBack();
this.context.router.goBack();
Gives error:
给出错误:
TypeError: null is not an object (evaluating 'this.context')
类型错误:null 不是对象(评估“this.context”)
this.props.history.push('/');
this.props.history.push('/');
Gives error:
给出错误:
TypeError: null is not an object (evaluating 'this.props')
类型错误:null 不是对象(评估“this.props”)
Posting the Page1code here below:
Page1在下面发布代码:
import React, {Component} from 'react';
import {Button} from 'react-bootstrap';
class Page1 extends Component {
constructor(props) {
super(props);
this.handleNext = this.handleNext.bind(this);
}
handleNext() {
this.props.history.push('/page2');
}
handleBack() {
this.props.history.push('/');
}
/*
* Main render method of this class
*/
render() {
return (
<div>
{/* some component code */}
<div className="navigationButtonsLeft">
<Button onClick={this.handleBack} bsStyle="success">< Back</Button>
</div>
<div className="navigationButtonsRight">
<Button onClick={this.handleNext} bsStyle="success">Next ></Button>
</div>
</div>
);
}
export default Page1;
回答by Vivek Doshi
I think the issue is with binding:
我认为问题在于绑定:
constructor(props){
super(props);
this.goBack = this.goBack.bind(this); // i think you are missing this
}
goBack(){
this.props.history.goBack();
}
.....
<button onClick={this.goBack}>Go Back</button>
As I have assumed before you posted the code:
正如我在您发布代码之前假设的那样:
constructor(props) {
super(props);
this.handleNext = this.handleNext.bind(this);
this.handleBack = this.handleBack.bind(this); // you are missing this line
}
回答by Hoang Trinh
this.props.history.goBack();
This is the correct solution for react-router v4
这是 react-router v4 的正确解决方案
But one thing you should keep in mind is that you need to make sure this.props.history is existed.
但是你应该记住的一件事是你需要确保 this.props.history 存在。
That means you need to call this function this.props.history.goBack();inside the component that is wrapped by < Route/>
这意味着你需要在this.props.history.goBack();<Route/> 包裹的组件内部调用这个函数
If you call this function in a component that deeper in the component tree, it will not work.
如果您在组件树中更深的组件中调用此函数,它将不起作用。
EDIT:
编辑:
If you want to have history object in the component that is deeper in the component tree (which is not wrapped by < Route>), you can do something like this:
如果你想在组件树中更深的组件中拥有历史对象(它没有被 <Route> 包裹),你可以这样做:
...
import {withRouter} from 'react-router-dom';
class Demo extends Component {
...
// Inside this you can use this.props.history.goBack();
}
export default withRouter(Demo);
回答by frippera
For use with React Router v4 and a functional component anywhere in the dom-tree.
与 React Router v4 和 dom-tree 中任何位置的功能组件一起使用。
import React from 'react';
import { withRouter } from 'react-router-dom';
const GoBack = ({ history }) => <img src="./images/back.png" onClick={() => history.goBack()} alt="Go back" />;
export default withRouter(GoBack);
回答by foureyedraven
Each answer here has parts of the total solution. Here's the complete solution that I used to get it to work inside of components deeper than where Route was used:
这里的每个答案都有整体解决方案的一部分。这是我用来让它在比使用 Route 更深的组件内部工作的完整解决方案:
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
^ You need that second line to import function and to export component at bottom of page.
^ 您需要第二行来导入函数并导出页面底部的组件。
render() {
return (
...
<div onClick={() => this.props.history.goBack()}>GO BACK</div>
)
}
^ Required the arrow function vs simply onClick={this.props.history.goBack()}
^ 需要箭头函数而不是简单的 onClick={this.props.history.goBack()}
export default withRouter(MyPage)
^ wrap your component's name with 'withRouter()'
^ 用 'withRouter()' 包裹你的组件名称
回答by Alfredo Re
Can you provide the code where you use this.props.history.push('/Page2');?
你能提供你使用的代码this.props.history.push('/Page2');吗?
Have you tried the goBack() method?
您是否尝试过 goBack() 方法?
this.props.history.goBack();
this.props.history.goBack();
It's listed here https://reacttraining.com/react-router/web/api/history
它列在这里https://reacttraining.com/react-router/web/api/history
With a live example here https://reacttraining.com/react-router/web/example/modal-gallery
这里有一个活生生的例子https://reacttraining.com/react-router/web/example/modal-gallery
回答by Rodius
Try:
尝试:
this.props.router.goBack()
回答by IamMHussain
Simply use
只需使用
<span onClick={() => this.props.history.goBack()}>Back</span>
回答by Lawrence Eagles
Here is the cleanest and simplest way you can handle this problem, which also nullifies the probable pitfalls of the this keyword. Use functional components:
这是您可以处理此问题的最干净、最简单的方法,它也消除了this keyword. 使用功能组件:
import { withRouter } from "react-router-dom";wrap your componentor better App.jswith the withRouter()HOCthis makes historyto be available "app-wide". wrapping your component only makes history available for that specificcomponent``` your choice.
import { withRouter } from "react-router-dom";用它包装您的component或更好的产品App.js,withRouter()HOC使其history在“应用程序范围内”可用。包装你的组件只会让history available for that specificcomponent```成为你的选择。
So you have:
所以你有了:
export default withRouter(App);In a Redux environment
export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), );you should even be able to userhistoryfrom your action creators this way.
export default withRouter(App);在 Redux 环境中,
export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), );您甚至应该能够以history这种方式从您的动作创建者中使用。
in your componentdo the following:
在你component做以下事情:
import {useHistory} from react-router-dom;
import {useHistory} from react-router-dom;
const history = useHistory(); // do this inside the component
const history = useHistory(); // do this inside the component
goBack = () => history.goBack();
goBack = () => history.goBack();
<btn btn-sm btn-primary onclick={goBack}>Go Back</btn>
<btn btn-sm btn-primary onclick={goBack}>Go Back</btn>
export default DemoComponent;
export default DemoComponent;
Gottcha useHistoryis only exported from the latest v5.1 react-router-domso be sure to update the package. However, you should not have to worry.
about the many snags of the this keyword.
GottchauseHistory仅从最新的 v5.1 导出,react-router-dom因此请务必更新包。但是,您不必担心。关于this keyword.
You can also make this a reusable component to use across your app.
您还可以将其设为可重用组件以在您的应用程序中使用。
function BackButton({ children }) {
let history = useHistory()
return (
<button type="button" onClick={() => history.goBack()}>
{children}
</button>
)
}```
Cheers.
回答by Nick Bristol
Hope this will help someone:
希望这会帮助某人:
import React from 'react';
import * as History from 'history';
import { withRouter } from 'react-router-dom';
interface Props {
history: History;
}
@withRouter
export default class YourComponent extends React.PureComponent<Props> {
private onBackClick = (event: React.MouseEvent): void => {
const { history } = this.props;
history.goBack();
};
...
回答by Julia Ramos
Maybe this can help someone.
也许这可以帮助某人。
I was using history.replace()to redirect, so when i tried to use history.goBack(), i was send to the previous page before the page i was working with.
So i changed the method history.replace()to history.push()so the history could be saved and i would be able to go back.
我正在使用history.replace()重定向,所以当我尝试使用时history.goBack(),我被发送到我正在使用的页面之前的上一页。所以我将方法更改history.replace()为history.push()这样可以保存历史记录并且我可以回去。

