react-router(v4)怎么回去?

Aks*_*kur 47 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>
Run Code Online (Sandbox Code Playgroud)

为了转发到后续页面,我只是这样做:

this.props.history.push('/Page2');
Run Code Online (Sandbox Code Playgroud)

但是,我怎样才能回到上一页?尝试了下面提到的一些事情,但没有运气: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;
Run Code Online (Sandbox Code Playgroud)

Viv*_*shi 68

我认为问题在于绑定:

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>
Run Code Online (Sandbox Code Playgroud)

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

constructor(props) {
    super(props);
    this.handleNext = this.handleNext.bind(this);
    this.handleBack = this.handleBack.bind(this); // you are missing this line
}
Run Code Online (Sandbox Code Playgroud)


Hoa*_*inh 15

this.props.history.goBack();
Run Code Online (Sandbox Code Playgroud)

这是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);
Run Code Online (Sandbox Code Playgroud)


fou*_*ven 11

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

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
Run Code Online (Sandbox Code Playgroud)

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

render() {
  return (
  ...
    <div onClick={() => this.props.history.goBack()}>GO BACK</div>
  )
}
Run Code Online (Sandbox Code Playgroud)

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

export default withRouter(MyPage)
Run Code Online (Sandbox Code Playgroud)

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


小智 9

与dom树中任何地方的React Router v4和功能组件一起使用。

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);
Run Code Online (Sandbox Code Playgroud)


小智 7

Here is the cleanest and simplest way you can handle this problem, which also nullifies the probable pitfalls of the this keyword. Use functional components:

import { withRouter } from "react-router-dom"; wrap your component or better App.js with the withRouter() HOC this makes history to be available "app-wide". wrapping your component only makes history available for that specific component``` your choice.

So you have:

  1. export default withRouter(App);

  2. In a Redux environment export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), ); you should even be able to user history from your action creators this way.

in your component do the following:

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;

Gottcha useHistory is only exported from the latest v5.1 react-router-dom so be sure to update the package. However, you should not have to worry. about the many snags of the this keyword.

You can also make this a reusable component to use across your app.


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

Run Code Online (Sandbox Code Playgroud)

  • 谢谢。但是,为什么当我返回浏览器时我的组件没有重新渲染? (3认同)

Alf*_* Re 5

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

您是否尝试过 goBack() 方法?

this.props.history.goBack();

它列在这里https://reacttraining.com/react-router/web/api/history

这里有一个活生生的例子https://reacttraining.com/react-router/web/example/modal-gallery