javascript - react-router (v4) 怎么回去?

标签 javascript reactjs react-router-v4

试图弄清楚如何才能返回到上一页。我正在使用 [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();

给出错误:

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

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

给出错误:

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

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

给出错误:

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;

最佳答案

我认为问题在于绑定(bind):

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
}

关于javascript - react-router (v4) 怎么回去?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46681387/

相关文章:

javascript - JSHint Backbone 未在 CodeKit 中定义

javascript - AngularJS $resource - X 毫秒后调用后备 URL

javascript - 如何让我的机器人向另一个 channel 发送消息?

javascript - 重定向到 App.js 中 componentDidMount 上的 url

reactjs - React-router-dom v4 404 pageNotFound <路由路径 ="*".../> 不工作

访问 URL 参数的 ReactJS PrivateRoute

javascript - 自执行匿名函数并再次调用

javascript - 如何在 react 中显示图像数组中的图像

javascript - 使用 for-each 和 props 更改状态值

reactjs - 使用 React DatePicker 时禁用移动浏览器上的键盘