有没有人能告诉我如何回到上一页,而不是具体的路线?

当使用此代码时:

var BackButton = React.createClass({

 mixins: [Router.Navigation],
  render: function() {
    return (
        <button
            className="button icon-left"
            onClick={this.navigateBack}>
            Back
        </button>
    );
  },

  navigateBack: function(){
    this.goBack();
  }
});

得到这个错误,goBack()被忽略,因为没有路由器历史

以下是我的路线:

// Routing Components
Route = Router.Route;
RouteHandler = Router.RouteHandler;
DefaultRoute = Router.DefaultRoute;

var routes = (
 <Route name="app" path="/" handler={OurSchoolsApp}>
     <DefaultRoute name="home" handler={HomePage} />
     <Route name="add-school" handler={AddSchoolPage}  />
     <Route name="calendar" handler={CalendarPage}  />
     <Route name="calendar-detail" path="calendar-detail/:id" handler={CalendarDetailPage} />
     <Route name="info-detail" path="info-detail/:id" handler={InfoDetailPage} />
     <Route name="info" handler={InfoPage} />
     <Route name="news" handler={NewsListPage} />
     <Route name="news-detail" path="news-detail/:id" handler={NewsDetailPage} />
     <Route name="contacts" handler={ContactPage} />
     <Route name="contact-detail" handler={ContactDetailPage} />
     <Route name="settings" handler={SettingsPage} />
 </Route>
 );

 Router.run(routes, function(Handler){
   var mountNode = document.getElementById('app');
   React.render(<Handler /> , mountNode);
 });

当前回答

返回指定页面:

  import { useHistory } from "react-router-dom";

  const history = useHistory();
  
  const routeChange = () => {
    let path = '/login';
    history.push(path);
  };

返回上一页:

  import { useHistory } from "react-router-dom";

  const history = useHistory();
  
  const routeChange = () => {
    history.goBack()
  };

其他回答

这是一个工作的BackButton组件(React 0.14):

var React = require('react');
var Router = require('react-router');

var History = Router.History;

var BackButton = React.createClass({
  mixins: [ History ],
  render: function() {
    return (
      <button className="back" onClick={this.history.goBack}>{this.props.children}</button>
    );
  }
});

module.exports = BackButton;

如果没有历史记录,你当然可以这样做:

<button className="back" onClick={goBack}>{this.props.children}</button>

function goBack(e) {
  if (/* no history */) {
    e.preventDefault();
  } else {
    this.history.goBack();
  }
}

更新React v16和ReactRouter v4.2.0(2017年10月):

class BackButton extends Component {
  static contextTypes = {
    router: () => true, // replace with PropTypes.object if you use them
  }

  render() {
    return (
      <button
        className="button icon-left"
        onClick={this.context.router.history.goBack}>
          Back
      </button>
    )
  }
}

更新React v15和ReactRouter v3.0.0(2016年8月):

var browserHistory = ReactRouter.browserHistory;

var BackButton = React.createClass({
  render: function() {
    return (
      <button
        className="button icon-left"
        onClick={browserHistory.goBack}>
        Back
      </button>
    );
  }
});

创建了一个稍微复杂一点的嵌入iframe的例子:https://jsfiddle.net/kwg1da3a/

React v14和ReacRouter v1.0.0(2015年9月10日)

你可以这样做:

var React = require("react");
var Router = require("react-router");

var SomePage = React.createClass({
  ...

  contextTypes: {
    router: React.PropTypes.func
  },
  ...

  handleClose: function () {
    if (Router.History.length > 1) {
      // this will take you back if there is history
      Router.History.back();
    } else {
      // this will take you to the parent route if there is no history,
      // but unfortunately also add it as a new route
      var currentRoutes = this.context.router.getCurrentRoutes();
      var routeName = currentRoutes[currentRoutes.length - 2].name;
      this.context.router.transitionTo(routeName);
    }
  },
  ...

你需要小心,你有必要的历史回溯。如果你直接点击页面,然后再点击返回,它会带你回到应用之前的浏览器历史。

这个解决方案可以兼顾这两种情况。但是,它不会处理可以在页面中导航(并添加到浏览器历史记录中)的iframe(使用后退按钮)。坦白地说,我认为这是反应路由器的一个bug。问题创建在这里:https://github.com/rackt/react-router/issues/1874

回来的

你也可以使用react-router-redux,它有goBack()和push()。

下面是一个样本包:

在你的应用程序的入口点,你需要ConnectedRouter,有时需要连接的一个棘手的连接是history对象。Redux中间件监听历史更改:

import React from 'react'
import { render } from 'react-dom'
import { ApolloProvider } from 'react-apollo'
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'react-router-redux'
import client from './components/apolloClient'
import store, { history } from './store'
import Routes from './Routes'
import './index.css'

render(
  <ApolloProvider client={client}>
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <Routes />
      </ConnectedRouter>
    </Provider>
  </ApolloProvider>,
  document.getElementById('root'),
)

我会告诉你一个连接历史的方法。注意历史记录是如何导入到商店的,也可以作为一个单例导出,这样它就可以在应用程序的入口点使用:

import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory'
import rootReducer from './reducers'

export const history = createHistory()

const initialState = {}
const enhancers = []
const middleware = [thunk, routerMiddleware(history)]

if (process.env.NODE_ENV === 'development') {
  const { devToolsExtension } = window
  if (typeof devToolsExtension === 'function') {
    enhancers.push(devToolsExtension())
  }
}

const composedEnhancers = compose(applyMiddleware(...middleware), ...enhancers)
const store = createStore(rootReducer, initialState, composedEnhancers)

export default store

上面的示例块展示了如何加载react-router-redux中间件帮助程序来完成设置过程。

我认为接下来的部分完全是额外的,但我将包括它,以防将来有人发现好处:

import { combineReducers } from 'redux'
import { routerReducer as routing } from 'react-router-redux'

export default combineReducers({
  routing, form,
})

我一直在使用routerReducer,因为它允许我强制重载组件,而通常情况下由于shouldComponentUpdate而无法重载组件。一个明显的例子是当你有一个导航栏,当用户按下导航链接按钮时,它应该更新。如果您沿着这条路走下去,您将了解到Redux的连接方法使用shouldComponentUpdate。使用routerReducer,你可以使用mapStateToProps将路由更改映射到导航栏中,这将在历史对象更改时触发它更新。

是这样的:

const mapStateToProps = ({ routing }) => ({ routing })

export default connect(mapStateToProps)(Nav)

请原谅我为人们添加了一些额外的关键字:如果您的组件没有正确更新,请通过删除连接函数来调查shouldComponentUpdate,看看它是否修复了问题。如果是这样,拉入routerReducer,当URL改变时,组件就会正确更新。

最后,在完成所有这些之后,您可以随时调用goBack()或push() !

现在尝试一些随机的组件:

在connect()中导入 你甚至不需要mapStateToProps或者mapDispatchToProps 从react-router-redux导入goBack和push 调用this.props.dispatch(返回()) 调用this.props.dispatch (push(' /三明治')) 体验积极情绪

如果你需要更多的样本,请访问:https://www.npmjs.com/package/react-router-redux

React路由器v6

useNavigate Hook是现在返回的推荐方式:

import { useNavigate } from 'react-router-dom';

function App() {
  const navigate = useNavigate();

  return (
    <>
      <button onClick={() => navigate(-1)}>go back</button>
      <button onClick={() => navigate(1)}>go forward</button>
    </>
  );
}

Codesandbox样本

Go back/forward multiple history stack entries:
<button onClick={() => navigate(-2)}>go two back</button>
<button onClick={() => navigate(2)}>go two forward</button>
Go to specific route:
navigate("users") // go to users route, like history.push
navigate("users", { replace: true }) // go to users route, like history.replace
navigate("users", { state }) // go to users route, pass some state in

usenavate取代了useHistory以更好地支持即将到来的React悬疑/并发模式。

对我有用的是在我的文件顶部导入使用throuter;

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

然后用它来包装导出的函数在我的文件底部;

export default withRouter(WebSitePageTitleComponent)

然后允许我访问路由器的历史道具。完整的示例代码如下!

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

import PropTypes from 'prop-types'

class TestComponent extends Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    event.preventDefault()
    this.props.history.goBack()
  }

  render() {
    return (
      <div className="page-title">
        <a className="container" href="/location" onClick={this.handleClick}>
          <h1 className="page-header">
            { this.props.title }
          </h1>
        </a>
      </div>
    )
  }
}

const { string, object } = PropTypes

TestComponent.propTypes = {
  title: string.isRequired,
  history: object
}

export default withRouter(TestComponent)