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

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

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

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


当前回答

React路由器v6

我已经有一段时间没有接触过React了,但我想感谢并强调Shimrit Snapir的以下评论:

在React Router 6.0上,<Redirect/>更改为<Navigator/>

React路由器V4

tl:dr;

if (navigate) {
  return <Redirect to="/" push={true} />
}

简单而声明性的答案是,需要将<Redirectto={URL}push={boolean}/>与setState()结合使用

push:boolean-如果为true,重定向将向历史中推送一个新条目,而不是替换当前条目。


import { Redirect } from 'react-router'

class FooBar extends React.Component {
  state = {
    navigate: false
  }

  render() {
    const { navigate } = this.state

    // Here is the important part
    if (navigate) {
      return <Redirect to="/" push={true} />
    }
   // ^^^^^^^^^^^^^^^^^^^^^^^

    return (
      <div>
        <button onClick={() => this.setState({ navigate: true })}>
          Home
        </button>
      </div>
    )
  }
}

这里有一个完整的例子。在这里阅读更多信息。

PS.该示例使用ES7+属性初始化器初始化状态。如果你感兴趣的话,也可以看看这里。

其他回答

在基于类的组件中编程导航。

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

class MyComponent extends React.Component{
    state = {rpath: null}

    const goTo = (path) => this.setState({rpath: path});

    render(){
        if(this.state.rpath){
            return <Redirect to={this.state.rpath}/>
        }
        .....
        .....
    }
}

在写作时,正确的答案适合我

this.context.router.history.push('/');

但您需要将PropTypes添加到组件中

Header.contextTypes = {
  router: PropTypes.object.isRequired
}
export default Header;

不要忘记导入PropTypes

import PropTypes from 'prop-types';

以下是最简单、最干净的方法,大约是当前的React Router 3.0.0和ES6:

使用ES6反应路由器3.x.x:

import { withRouter } from 'react-router';

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

// Export the decorated class
export default withRouter(Example);

或者,如果不是默认类,则导出如下:

withRouter(Example);
export { Example };

注意,在3.x.x中,<Link>组件本身使用router.push,因此您可以传递任何传递<Linkto=标记的内容,例如:

   this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'

要将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即将推出,现在有了一种新的实现方式。

import { MemoryRouter, BrowserRouter } from 'react-router';

const navigator = global && global.navigator && global.navigator.userAgent;
const hasWindow = typeof window !== 'undefined';
const isBrowser = typeof navigator !== 'undefined' && navigator.indexOf('Node.js') === -1;
const Router = isBrowser ? BrowserRouter : MemoryRouter;

<Router location="/page-to-go-to"/>

react lego是一个示例应用程序,展示了如何使用/更新react router,它包括导航应用程序的示例功能测试。