代码之家  ›  专栏  ›  技术社区  ›  Akshay Lokur

反应路由器(v4)如何返回?

  •  120
  • Akshay Lokur  · 技术社区  · 9 年前

    我想知道怎样才能回到上一页。我正在使用 [react-router-v4][1]

    这是我在第一个登录页中配置的代码:

    <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>
    

    为了转发到后续页面,我只需执行以下操作:

    this.props.history.push('/Page2');
    

    然而,我怎样才能回到上一页? 尝试了以下几件事,但运气不佳: 1. this.props.history.goBack();

    1. this.context.router.goBack();

    给出错误:

    TypeError:null不是对象(计算“this.context”)

    1. this.props.history.push('/');

    给出错误:

    TypeError:null不是对象(计算“this.props”)

    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">&lt; Back</Button>
            </div>
            <div className="navigationButtonsRight">
              <Button onClick={this.handleNext} bsStyle="success">Next &gt;</Button>
            </div>
    
          </div>
        );
      }
    
    
    export default Page1;
    
    14 回复  |  直到 9 年前
        1
  •  151
  •   Vivek Doshi    9 年前

    我认为问题在于约束:

    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>
    

    正如我在您发布代码之前所假设的那样:

    constructor(props) {
        super(props);
        this.handleNext = this.handleNext.bind(this);
        this.handleBack = this.handleBack.bind(this); // you are missing this line
    }
    
        2
  •  66
  •   0xh8h    5 年前

    更新日期:

    现在我们有了钩子,所以我们可以使用 useHistory

    const history = useHistory()
    
    const goBack = () => {
      history.goBack()
    }
    
    return (
      <button type="button" onClick={goBack}>
        Go back
      </button>
    );
    

    this.props.history.goBack();
    

    这是react路由器v4的正确解决方案

    这意味着您需要调用此函数 this.props.history.goBack(); 在由<路线/>

    如果在组件树中较深的组件中调用此函数,它将不起作用。

    编辑:

    ...
    import {withRouter} from 'react-router-dom';
    
    class Demo extends Component {
        ...
        // Inside this you can use this.props.history.goBack();
    }
    
    export default withRouter(Demo);
    
        3
  •  19
  •   frippera    8 年前

    用于React路由器v4和dom树中任何位置的功能组件。

    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);
    
        4
  •  11
  •   foureyedraven    7 年前

    这里的每个答案都有整体解决方案的一部分。这是我用来让它在组件内部工作的完整解决方案,比使用路由的地方更深:

    import React, { Component } from 'react'
    import { withRouter } from 'react-router-dom'
    

    ^您需要第二行来导入函数和导出页面底部的组件。

    render() {
      return (
      ...
        <div onClick={() => this.props.history.goBack()}>GO BACK</div>
      )
    }
    

    ^需要箭头函数vs simply onClick={this.props.history.goBack()}

    export default withRouter(MyPage)
    

    ^用“withRouter()”包装组件名称

        5
  •  7
  •   Mazyod    5 年前

    以下是处理此问题的最干净、最简单的方法,这也消除了 this keyword . 使用功能组件:

    import { withRouter } from "react-router-dom"; 包裹你的 component App.js 和 withRouter() HOC 这使得 history 在“应用程序范围”可用。包装组件只会 history available for that specific 组件``由您选择。

    所以你有:

    1. export default withRouter(App);

    2. 在Redux环境中 export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), ); 你甚至应该能够使用 历史 从你的动作创造者那里。

    在你的 组成部分 执行以下操作:

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

    const history = useHistory(); // do this inside the component

    goBack = () => history.goBack();

    <btn btn-sm btn-primary onclick={goBack}>Go Back</btn>

    export default DemoComponent;

    哥查 useHistory 仅从最新的v5.1导出 react-router-dom 所以一定要更新包。然而,你不必担心。 关于 .

    您还可以将其作为一个可重用组件,在应用程序中使用。

    
    function BackButton({ children }) {
      let history = useHistory()
      return (
        <button type="button" onClick={() => history.goBack()}>
          {children}
        </button>
      )
    }```
    Cheers.
    
    
        6
  •  5
  •   Alfredo Re    9 年前

    你能提供你使用的代码吗 this.props.history.push('/Page2'); ?

    this.props.history.goBack();

    这里列出了 https://reacttraining.com/react-router/web/api/history

    https://reacttraining.com/react-router/web/example/modal-gallery

        7
  •  4
  •   Tovi Newman    5 年前

    import { useHistory } from "react-router-dom";
    const history = useHistory();
    history.go(-1);
    
        8
  •  3
  •   David S    4 年前

    更新2022 w V6

    navigate(-1)
    

    要从历史记录中删除当前页面,请执行以下操作:

    navigate(-1, { replace: true })
    
        9
  •  0
  •   Rodius    9 年前

    尝试:

    this.props.router.goBack()
    
        10
  •  0
  •   IamMHussain    8 年前

    简单使用

    <span onClick={() => this.props.history.goBack()}>Back</span>
    
        11
  •  0
  •   Nick Bristol    6 年前

    希望这能帮助别人:

    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();
      };
    
    ...
    
        12
  •  0
  •   Julia Ramos    6 年前

    也许这可以帮助别人。

    我正在使用 history.replace() history.goBack() ,我被发送到我正在使用的页面之前的上一页。 所以我改变了方法 到 history.push() 所以历史可以被保存,我可以回到过去。

        13
  •  0
  •   user14199788    6 年前

    我不确定是否有其他人遇到了这个问题,或者可能需要看到这个问题。但我花了大约3个小时试图解决这个问题:

    我想在点击按钮时实现一个简单的goBack()。我以为我有了一个好的开始,因为我的应用程序。js已经包装在路由器中,我正在从“react Router dom”导入{BrowserRouter as Router}。。。因为路由器元素允许我评估历史对象。

    前任:

    import React from 'react';
    import './App.css';
    import Splash from './components/Splash';
    import Header from './components/Header.js';
    import Footer from './components/Footer';
    import Info from './components/Info';
    import Timer from './components/Timer';
    import Options from './components/Options';
    import { BrowserRouter as Router, Route } from 'react-router-dom';
    function App() {
      return (
        <Router>
          <Header />
          <Route path='/' component={Splash} exact />
          <Route path='/home' component={Info} exact />
          <Route path='/timer' component={Timer} exact />
          <Route path='/options' component={Options} exact />
          <Footer />
        </Router>
      );
    }
    export default App;
    

    但问题出在我的导航(子组件)模块上, 我必须从“react router dom”中“导入{withRouter}” 然后强制导出:

    export default withRouter(Nav);
    

    前任:

    import React from 'react';
    import { withRouter } from 'react-router-dom';
    class Nav extends React.Component {
        render() {
            return (
                <div>
                    <label htmlFor='back'></label>
                    <button id='back' onClick={ () => this.props.history.goBack() }>Back</button>
                    <label htmlFor='logOut'></label>
                    <button id='logOut' ><a href='./'>Log-Out</a>            
    </button>
                </div>
            );
        }
    }
    export default withRouter(Nav);
    

        14
  •  0
  •   Zeeshan Safdar    5 年前

    您可以使用 history.goBack() 在功能组件中。就像这样。

    import { useHistory } from 'react-router';
    const component = () => { 
      const history = useHistory();
    
      return (
       <button onClick={() => history.goBack()}>Previous</button>
      )
    }