react-router(v4)怎么回去? [英] react-router (v4) how to go back?

查看:158
本文介绍了react-router(v4)怎么回去?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图弄清楚如何返回上一页。我正在使用 [react-router-v4] [1]

Trying to figure out how can I go back to the previous page. I am using [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');

但是,我该如何回到上一页?
尝试了下面提到的一些事情,但没有运气:
1. this.props.history.goBack();

However, how can I go back to previous page? Tried few things like mentioned below but no luck: 1. this.props.history.goBack();

给出错误:


TypeError:null不是对象(评估'this.props')

TypeError: null is not an object (evaluating 'this.props')




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

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

给出错误:


TypeError:null不是对象(评估'this.context')

TypeError: null is not an object (evaluating 'this.context')




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

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

给出错误:


TypeError:null不是对象(评估'this.props')

TypeError: null is not an object (evaluating '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;


推荐答案

我认为问题在于绑定:

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
}

这篇关于react-router(v4)怎么回去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆