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

当使用此代码时:

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);
 });

当前回答

看看我使用React 16.0和React-router v4的工作示例。查看代码Github

使用withRouter和history.goBack()

这就是我正在实现的想法……

History.js

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'
import './App.css'


class History extends Component {

  handleBack = () => {
    this.props.history.goBack()
  }

  handleForward = () => {
    console.log(this.props.history)
    this.props.history.go(+1)
  }

  render() {
    return <div className="container">
      <div className="row d-flex justify-content-between">
        <span onClick={this.handleBack} className="d-flex justify-content-start button">
          <i className="fas fa-arrow-alt-circle-left fa-5x"></i>
        </span>
        <span onClick={this.handleForward} className="d-flex justify-content-end button">
          <i className="fas fa-arrow-alt-circle-right fa-5x"></i>
        </span>
      </div>
    </div>
  }
}

export default withRouter(History)

PageOne.js

import React, { Fragment, Component } from 'react'

class PageOne extends Component {

   componentDidMount(){
      if(this.props.location.state && this.props.location.state.from != '/pageone')
      this.props.history.push({
         pathname: '/pageone',
         state: { 
             from: this.props.location.pathname
         }
       });
   }

   render() {
      return (
         <Fragment>
            <div className="container-fluid">
               <div className="row d-flex justify-content-center">
                  <h2>Page One</h2>
               </div>
            </div>
         </Fragment>
      )
   }
}

export default PageOne

另外,抱歉代码太大,不能全部贴在这里

其他回答

对我有用的是在我的文件顶部导入使用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)

在react-router v6中,当你想返回到前一页时,你可以使用useNavigate:

步骤1:

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

步骤2:

const navigate = useNavigate();

第三步:如果你想回到前一页,使用navigate(-1):

<button onClick={() => navigate(-1)}> Back </button>

回来的

你也可以使用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路由器使用HTML5 History API,它建立在浏览器历史API的基础上,提供了一个我们可以在React应用程序中轻松使用的接口。历史API。所以不需要导入任何东西(useHistory等)

对于功能组件:

<button onClick={()=>{ window.history.back() }}> Back </button>

对于类组件:

<button onClick={()=>{ this.window.history.back() }}> Back </button>

这段代码将为您完成任务。

this.context.router.history.goBack()