使用react router,我可以使用Link元素来创建由react route本地处理的链接。

我看到它在内部调用this.context.transitionTo(…)。

我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?

我看到了导航混合,但我可以在没有混合的情况下这样做吗?


当前回答

只需使用this.props.history.push('/where/to/go');

其他回答

在React Router v4中实现这一点时面临问题的人。

这里有一个从redux操作导航到React应用程序的工作解决方案。

文件history.js

import createHistory from 'history/createBrowserHistory'

export default createHistory()

文件App.js/Route.jsx

import { Router, Route } from 'react-router-dom'
import history from './history'
...
<Router history={history}>
 <Route path="/test" component={Test}/>
</Router>

文件*另一个_File.js或redux文件

import history from './history'

history.push('/test') // This should change the URL and rerender Test component

感谢GitHub上的评论:ReactTraining问题评论

这对我有效,不需要特殊进口:

<input 
  type="button" 
  name="back" 
  id="back" 
  class="btn btn-primary" 
  value="Back" 
  onClick={() => { this.props.history.goBack() }} 
/>

React路由器v4和ES6

您可以使用Router和this.props.history.push。

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

class Home extends Component {

    componentDidMount() {
        this.props.history.push('/redirect-to');
    }
}

export default withRouter(Home);

这可能不是最好的方法,但。。。使用react router v4,下面的TypeScript代码可以为一些人提供一些想法。

在下面的渲染组件(例如LoginPage)中,可以访问router对象,只需调用router.transitionTo('/home')即可导航。

导航代码取自。

“react router”:“^4.0.0-2”,“反应”:“^15.3.1”,

从“react Router/BrowserRouter”导入路由器;从“react History/BrowserHistory”导入{History};从“history/createBrowserHistory”导入createHistory;consthistory=createHistory();接口MatchWithPropsInterface{component:React.component的类型,router:路由器,历史:历史,确切地?:任何图案:字符串}类MatchWithProps扩展React.Component<MatchWithPropsInterface,any>{render(){返回(<Match{…this.props}render={(matchProps)=>(React.createElement(this.props.component,this.props))}/>)}}ReactDOM.渲染(<路由器>{({路由器})=>(<div><MatchWithProps justly pattern=“/”component={LoginPage}router={router}history={history}/><MatchWithProps pattern=“/login”component={LoginPage}router={router}history={history}/><MatchWithProps pattern=“/home”component={homepage}router={router}history={history}/><缺少组件={NotFoundView}/></div>)}</路由器>,document.getElementById('app'));

对于React路由器v4+

假设在初始渲染过程中不需要导航(可以使用<Redirect>组件),这就是我们在应用程序中所做的。

定义返回null的空路由。这将允许您访问历史对象。您需要在定义路由器的顶层执行此操作。

现在,您可以在历史上做所有可以做的事情,如history.push()、history.replace()、history.go(-1)等。!

import React from 'react';
import { HashRouter, Route } from 'react-router-dom';

let routeHistory = null;

export function navigateTo(path) {
  if(routeHistory !== null) {
    routeHistory.push(path);
  }
}

export default function App(props) {
  return (
    <HashRouter hashType="noslash">
      <Route
        render={({ history }) => {
          routeHistory = history;
          return null;
        }}
      />
      {/* Rest of the App */}
    </HashRouter>
  );
}