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

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

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

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


当前回答

如果您使用的是更新版本的React,那么使用“useHistory”钩子是最好的选择。

其他回答

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

React路由器v6+答案

TL;DR:您可以使用新的useNavigate钩子。

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

function Component() {
  let navigate = useNavigate();
  // Somewhere in your code, e.g. inside a handler:
  navigate("/posts"); 
}

useNavigate钩子返回一个可用于编程导航的函数。

反应路由器文档中的示例

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

function SignupForm() {
  let navigate = useNavigate();

  async function handleSubmit(event) {
    event.preventDefault();
    await submitForm(event.target);
    navigate("../success", { replace: true });
    // replace: true will replace the current entry in 
    // the history stack instead of adding a new one.

  }

  return <form onSubmit={handleSubmit}>{/* ... */}</form>;
}

React Router 5.1.0+应答(使用钩子和React>16.8)

您可以使用Functional Components上的useHistory挂钩,并以编程方式导航:

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

function HomeButton() {
  let history = useHistory();
  // use history.push('/some/path') here
};

React Router 4.0.0+答案

在4.0及以上版本中,将历史记录用作组件的道具。

class Example extends React.Component {
   // use `this.props.history.push('/some/path')` here
};

注意:如果<Route>未呈现组件,则此.props.history不存在。您应该使用<Route path=“…”component={YourComponent}/>在YourComponent中具有this.props.history

React路由器3.0.0+答案

在3.0及以上版本中,将路由器用作组件的道具。

class Example extends React.Component {
   // use `this.props.router.push('/some/path')` here
};

React路由器2.4.0+答案

在2.4及以上版本中,使用更高阶的组件将路由器作为组件的道具。

import { withRouter } from 'react-router';

class Example extends React.Component {
   // use `this.props.router.push('/some/path')` here
};

// Export the decorated class
var DecoratedExample = withRouter(Example);

// PropTypes
Example.propTypes = {
  router: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  }).isRequired
};

React Router 2.0.0+答案

此版本与1.x向后兼容,因此无需升级指南。仅仅通过这些例子就足够了。

也就是说,如果您希望切换到新模式,路由器内有一个browserHistory模块,您可以使用

从“react router”导入{browserHistory}

现在,您可以访问浏览器历史记录,因此可以执行推送、替换等操作。例如:

browserHistory.push('/some/path')

进一步阅读:历史和航行


React Router 1.x.x答案

我不会详细介绍升级。您可以在《升级指南》中阅读相关内容

这个问题的主要变化是从导航混合到历史。现在它使用浏览器历史记录API来更改路由,因此我们将从现在开始使用pushState()。

下面是使用Mixin的示例:

var Example = React.createClass({
  mixins: [ History ],
  navigateToHelpPage () {
    this.history.pushState(null, `/help`);
  }
})

请注意,此历史记录来自rackt/History项目。不是来自React Router本身。

如果您出于某种原因(可能是因为ES6类)不想使用Mixin,那么您可以从this.props.history中访问从路由器获得的历史记录。它将仅对路由器渲染的组件可用。因此,如果您想在任何子组件中使用它,则需要通过props将其作为属性传递。

您可以在他们的1.0.x文档中阅读有关新版本的更多信息

下面是一个关于在组件外部导航的帮助页面

它建议获取一个引用history=createHistory(),并对其调用replaceState。

React路由器0.13.x答案

我也遇到了同样的问题,只能通过带有react路由器的Navigation mixin找到解决方案。

我是这样做的

import React from 'react';
import {Navigation} from 'react-router';

let Authentication = React.createClass({
  mixins: [Navigation],

  handleClick(e) {
    e.preventDefault();

    this.transitionTo('/');
  },

  render(){
    return (<div onClick={this.handleClick}>Click me!</div>);
  }
});

我能够在不需要访问.context的情况下调用transitionTo()

或者你可以试试ES6高级课程

import React from 'react';

export default class Authentication extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    e.preventDefault();

    this.context.router.transitionTo('/');
  }

  render(){
    return (<div onClick={this.handleClick}>Click me!</div>);
  }
}

Authentication.contextTypes = {
  router: React.PropTypes.func.isRequired
};

React路由器Redux注意:如果您使用的是Redux,还有一个项目叫做React Router Redux为您提供redux绑定ReactRouter,使用与React Redux会

React Router Redux有一些可用的方法,允许从内部动作创建者进行简单的导航。对于在React Native中拥有现有架构的人来说,这些模式尤其有用,并且他们希望在React Web中以最小的样板开销使用相同的模式。

探索以下方法:

推(位置)替换(位置)go(数字)goBack()goForward()

以下是Redux Thunk的用法示例:

./actioncreators.js

import { goBack } from 'react-router-redux'

export const onBackPress = () => (dispatch) => dispatch(goBack())

./viewcomponent.js

<button
  disabled={submitting}
  className="cancel_button"
  onClick={(e) => {
    e.preventDefault()
    this.props.onBackPress()
  }}
>
  CANCEL
</button>

React Router 4.x答案

在我这一方面,我希望有一个单独的历史对象,我甚至可以携带外部组件。我喜欢按需导入一个history.js文件,并对其进行操作。

您只需将BrowserRouter更改为Router,并指定历史属性。这对你来说没有任何改变,除了你有自己的历史对象,你可以随心所欲地操纵它。

您需要安装历史记录,即react router使用的库。

示例用法,ES6表示法:

history.js

import createBrowserHistory from 'history/createBrowserHistory'
export default createBrowserHistory()

基本组件.js

import React, { Component } from 'react';
import history from './history';

class BasicComponent extends Component {

    goToIndex(e){
        e.preventDefault();
        history.push('/');
    }

    render(){
        return <a href="#" onClick={this.goToIndex}>Previous</a>;
    }
}

如果您必须从实际从Route组件渲染的组件进行导航,还可以从props访问历史,如下所示:

基本组件.js

import React, { Component } from 'react';

class BasicComponent extends Component {

    navigate(e){
        e.preventDefault();
        this.props.history.push('/url');
    }

    render(){
        return <a href="#" onClick={this.navigate}>Previous</a>;
    }
}

只需使用useNavigate from react router dom

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

const MYComponent = () => {
    const navigate = useNavigate();

    navigate("Xyz/MYRoutes");

 
}

export default MYComponent;

在代码中使用上述的useNavigate功能。

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,而不是实际导航到页面。