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

其他回答

对于ES6+React组件,以下解决方案适用于我。

我跟随费利佩·斯金纳,但添加了一个端到端解决方案,以帮助像我这样的初学者。

以下是我使用的版本:

“反应路由器”:“^2.7.0”“反应”:“^15.3.1”

下面是我的react组件,其中我使用react路由器进行编程导航:

import React from 'react';

class loginComp extends React.Component {
   constructor( context) {
    super(context);
    this.state = {
      uname: '',
      pwd: ''
    };
  }

  redirectToMainPage(){
        this.context.router.replace('/home');
  }

  render(){
    return <div>
           // skipping html code 
             <button onClick={this.redirectToMainPage.bind(this)}>Redirect</button>
    </div>;
  }
};

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

 module.exports = loginComp;

以下是路由器的配置:

 import { Router, Route, IndexRedirect, browserHistory } from 'react-router'

 render(<Router history={browserHistory}>
          <Route path='/' component={ParentComp}>
            <IndexRedirect to = "/login"/>
            <Route path='/login' component={LoginComp}/>
            <Route path='/home' component={HomeComp}/>
            <Route path='/repair' component={RepairJobComp} />
            <Route path='/service' component={ServiceJobComp} />
          </Route>
        </Router>, document.getElementById('root'));

在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入门

上面已经提到,我们可以使用useNavigate()在上一次更新React Router V6(不包括useHistory)中导航

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

const myComponent = () => {
  const navigate = useNavigate();
  navigate('my_url');
  ...
}

但我在这里找不到的是调用导航出React组件,就像将redux saga函数中的页面导航到另一个页面。以防万一,如果你有同样的问题,这是我发现的。

在根组件中(我称之为<App/>)

import { useNavigate } from 'react-router-dom';
import useBus from 'use-bus';

const App = () => {
  const navigate = useNavigate();
  useBus('@@ui/navigate', (action) => navigate(action.payload.url), []);
  ...
}

脱离React组件(在我的例子中是redux saga函数)

import { dispatch } from 'use-bus';

dispatch({ type: '@@ui/navigate', payload: { url: '/404' } });

希望有帮助!

如果您碰巧通过react router redux将RR4与redux配对,那么也可以使用react router-redux中的路由操作创建器。

import { push, replace, ... } from 'react-router-redux'

class WrappedComponent extends React.Component {
  handleRedirect(url, replaceState = true) {
    replaceState
      ? this.props.dispatch(replace(url))
      : this.props.dispatch(push(url))
  }
  render() { ... }
}

export default connect(null)(WrappedComponent)

如果您使用redux thunk/saga来管理异步流,请在redux操作中导入上述操作创建者,并使用mapDispatchToProps连接到React组件可能会更好。

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