react-router (v4) 怎么回去?

IT技术 javascript reactjs react-router-v4
2021-03-04 15:25:26

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

给出错误:

类型错误:null 不是对象(评估“this.props”)

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

给出错误:

类型错误:null 不是对象(评估“this.context”)

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

给出错误:

类型错误: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;
6个回答

我认为问题在于绑定:

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
}
当按下浏览器的后退按钮,在不工作componentDidUpdatewindow.onpopstate
2021-05-02 15:25:26

更新:

现在我们有了钩子,所以我们可以使用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();<Route/> 包裹的组件内部调用这个函数

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

编辑:

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

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

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

export default withRouter(Demo);
那么它如何工作呢?你怎么能从任何地方回到历史?
2021-04-21 15:25:26
感谢您对 withRouter 的编辑,为我修复了它。
2021-04-28 15:25:26
@Felipe:嗨,请检查我编辑过的答案。我认为它回答了你的问题。
2021-05-02 15:25:26
@Felipe 你可以从任何地方回去。我只是说你需要在 Container 组件中添加这行代码才能获得“history”对象,不要使用没有被 Route 包裹的 Presentational 组件中的这行代码(medium.com/@dan_abramov /smart-and-dumb-components-7ca2f9a7c7d0 )
2021-05-04 15:25:26

与 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);
胖箭头版本对我来说总是看起来更干净,谢谢。
2021-04-24 15:25:26
这是一个很好的解决方案,因为它不使用生命周期方法。它对我来说也更清楚,因为它表示通过了什么,在这种情况下是历史对象。
2021-05-18 15:25:26

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

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

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

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

^ 需要箭头函数而不是简单的 onClick={this.props.history.goBack()}

export default withRouter(MyPage)

^ 用 'withRouter()' 包裹你的组件名称

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

import { withRouter } from "react-router-dom"; 用它包装您的component或更好的产品App.jswithRouter() HOC使其history在“应用程序范围内”可用。包装你的组件只会让history available for that specific 组件``` 你的选择。

所以你有了:

  1. export default withRouter(App);

  2. 在 Redux 环境中, export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), );您甚至应该能够以history这种方式从您的动作创建者中使用。

在你component做以下事情:

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;

GottchauseHistory仅从最新的 v5.1 导出,react-router-dom因此请务必更新包。但是,您不必担心。关于this keyword.

您还可以将其设为可重用组件以在您的应用程序中使用。


function BackButton({ children }) {
  let history = useHistory()
  return (
    <button type="button" onClick={() => history.goBack()}>
      {children}
    </button>
  )
}```
Cheers.

谢谢。但是,当我返回浏览器时,为什么我的组件没有重新渲染?
2021-04-28 15:25:26