react-router (v4) 怎么回去?

react-router (v4) how to go back?

正在想办法返回上一页。我正在使用 [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;

尝试:

this.props.router.goBack()

你能提供你使用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

我认为问题在于绑定:

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
}

更新:

现在我们有了钩子,所以我们可以很容易地使用useHistory

const history = useHistory()

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

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

原版POST:

this.props.history.goBack();

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

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

这意味着你需要在

包裹的组件中调用这个函数 this.props.history.goBack();

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

编辑:

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

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

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

export default withRouter(Demo);

简单使用

<span onClick={() => this.props.history.goBack()}>Back</span>

用于 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);

这里的每个答案都是完整解决方案的一部分。这是我用来让它在比使用 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";withRouter() HOC 包装你的 component 或更好的 App.js 这使得 history 在“应用程序范围内”可用。包装您的组件只会使 history available for that specific component``` 成为您的选择。

所以你有:

  1. export default withRouter(App);

  2. 在 Redux 环境中 export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), ); 你甚至应该能够通过这种方式从你的 action creators 中使用 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;

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

的许多障碍

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


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

希望这会对某人有所帮助:

import React from 'react';
import * as History from 'history';
import { withRouter } from 'react-router-dom';

interface Props {
  history: History;
}

@withRouter
export default class YourComponent extends React.PureComponent<Props> {

  private onBackClick = (event: React.MouseEvent): void => {
    const { history } = this.props;
    history.goBack();
  };

...

也许这可以帮助某人。

我正在使用 history.replace() 进行重定向,所以当我尝试使用 history.goBack() 时,我被发送到我正在使用的页面之前的上一页。 所以我将方法 history.replace() 更改为 history.push() 这样可以保存历史记录并且我可以返回。

我不确定是否有其他人 运行 遇到这个问题或可能需要看这个。但是我花了大约 3 个小时试图解决这个问题:

我想通过单击按钮实现一个简单的 goBack()。我以为我有了一个好的开始,因为我的 App.js 已经包含在路由器中并且我正在从 'react-router-dom' 导入 { BrowserRouter as Router }; ... 因为 Router 元素允许我评估历史对象。

例如:

import React from 'react';
import './App.css';
import Splash from './components/Splash';
import Header from './components/Header.js';
import Footer from './components/Footer';
import Info from './components/Info';
import Timer from './components/Timer';
import Options from './components/Options';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
  return (
    <Router>
      <Header />
      <Route path='/' component={Splash} exact />
      <Route path='/home' component={Info} exact />
      <Route path='/timer' component={Timer} exact />
      <Route path='/options' component={Options} exact />
      <Footer />
    </Router>
  );
}
export default App;

但问题出在我的导航(子组件)模块上, 我不得不“从 'react-router-dom' 导入 {withRouter};” 然后强制导出:

export default withRouter(Nav);

例如:

import React from 'react';
import { withRouter } from 'react-router-dom';
class Nav extends React.Component {
    render() {
        return (
            <div>
                <label htmlFor='back'></label>
                <button id='back' onClick={ () => this.props.history.goBack() }>Back</button>
                <label htmlFor='logOut'></label>
                <button id='logOut' ><a href='./'>Log-Out</a>            
</button>
            </div>
        );
    }
}
export default withRouter(Nav);

总而言之,withRouter 是由于 React 中的一个已知问题而创建的,在某些情况下,当拒绝从路由器继承时,需要强制导出。

您可以在功能组件中使用history.goBack()。就这样。

import { useHistory } from 'react-router';
const component = () => { 
  const history = useHistory();

  return (
   <button onClick={() => history.goBack()}>Previous</button>
  )
}

如果使用 React Hooks 就这样做:

import { useHistory } from "react-router-dom";
const history = useHistory();
history.go(-1);

2022 年更新 V6

navigate(-1)

从历史记录中忽略当前页面:

navigate(-1, { replace: true })