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 不是一个对象(评估’this.props’)

  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;

原文由 Akshay Lokur 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 416
2 个回答

我认为问题在于绑定:

 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
}

原文由 Vivek Doshi 发布,翻译遵循 CC BY-SA 3.0 许可协议

更新:

现在我们有了钩子,所以我们可以使用 useHistory 轻松完成

const history = useHistory()

const goBack = () => {
  history.goBack()
}

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


原帖:

 this.props.history.goBack();

这是 react-router v4 的正确解决方案

但是你应该记住的一件事是你需要确保 this.props.history 存在。

这意味着你需要调用这个函数 this.props.history.goBack(); 在被包装的组件内部

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

编辑:

如果你想在组件树中更深的组件中拥有 history 对象(它没有被 包裹),你可以这样做:

 ...
import {withRouter} from 'react-router-dom';

class Demo extends Component {
    ...
    // Inside this you can use this.props.history.goBack();
}

export default withRouter(Demo);

原文由 0xh8h 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题