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

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

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

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


当前回答

React路由器v2

对于最新版本(v2.0.0-rc5),推荐的导航方法是直接推到历史单例。您可以在组件外部导航文档中看到这一点。

相关摘录:

import { browserHistory } from 'react-router';
browserHistory.push('/some/path');

如果使用更新的react router API,则需要在组件内部使用this.props中的历史记录,以便:

this.props.history.push('/some/path');

它还提供pushState,但对于每个记录的警告,它都是不推荐的。

如果使用react router redux,它提供了一个推送功能,您可以这样调度:

import { push } from 'react-router-redux';
this.props.dispatch(push('/some/path'));

然而,这可能仅用于更改URL,而不是实际导航到页面。

其他回答

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

要将withRouter与基于类的组件一起使用,请尝试以下操作。不要忘记将导出语句更改为与Router一起使用:

从“react router dom”导入{withRouter}

class YourClass extends React.Component {
  yourFunction = () => {
    doSomeAsyncAction(() =>
      this.props.history.push('/other_location')
    )
  }

  render() {
    return (
      <div>
        <Form onSubmit={ this.yourFunction } />
      </div>
    )
  }
}

export default withRouter(YourClass);

在React Router v4中,我遵循这两种方式以编程方式进行路由。

this.props.history.push(“/某物/某物”)this.props.history.replace(“/ssomething/something”)

第二个

替换历史堆栈上的当前条目

要获取道具中的历史记录,您可能必须使用

带路由器

InReact路由器v6

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

function Invoices() {
  let navigate = useNavigate();
  return (
    <div>
      <NewInvoiceForm
        onSubmit={async event => {
          let newInvoice = await createInvoice(event.target);
          navigate(`/invoices/${newInvoice.id}`);
        }}
      />
    </div>
  );
}

React Router v6入门

试试React Hook Router,“反应路由器的现代替代品”:

import { useRoutes, usePath, A} from "hookrouter";

要回答OP关于通过选择框链接的问题,您可以这样做:

navigate('/about');

更新的答案

我认为React Hook Router是一个很好的入门套件,帮助我学习了路由,但我后来更新了React Router,了解了它的历史和查询参数处理。

import { useLocation, useHistory } from 'react-router-dom';


const Component = (props) => {
    const history = useHistory();

    // Programmatically navigate
    history.push(newUrlString);
}

您可以将要导航到的位置推到历史位置。

以下是如何使用带有ES6的react router v2.0.0来实现这一点。react路由器已远离mixin。

import React from 'react';

export default class MyComponent extends React.Component {
  navigateToPage = () => {
    this.context.router.push('/my-route')
  };

  render() {
    return (
      <button onClick={this.navigateToPage}>Go!</button>
    );
  }
}

MyComponent.contextTypes = {
  router: React.PropTypes.object.isRequired
}