React Router Dom(4)以编程方式导航

时间:2018-05-30 13:44:34

标签: javascript reactjs react-router pusher react-router-dom

我正在开发一个“远程控制”的React应用程序,并尝试通过Pusher连接应用程序的标签导航。我正在使用react-router-dom并设置了我与Pusher的连接以及它在componentDidMount中监听的通道。我需要在每次返回消息时让应用程序更改URL导航,但无法弄清楚正确的“推送”方式是什么。我有许多关于以编程方式导航react-router-dom的线程,并尝试过this.history.push(),this.props.history.push(),它总是抛出历史未定义的错误。侦听器与路由本身位于同一个组件中。

    import React, { Component } from 'react';
    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
    import axios from 'axios';
    import Pusher from 'pusher-js';

    import Component1 from './Component1';
    import Component2 from './Component2';

    export default class AppRouter extends Component{

    componentDidMount() {
          const pusher = new Pusher('8675309', { cluster: 'us2', encrypted: true });
          const nav_channel = pusher.subscribe('nav');
          nav_channel.bind('message', data => { this.props.history.push(data.message) });
    }

...

render(){
    return(
      <Router>
        <Switch>
          <Route path='/path1' render={() => <Component1 navigate={this.handleNavChange} />} />
          <Route path="/path2" render={() => <Component2 navigate={this.handleNavChange} />} />

        </Switch>
      </Router>
    )
  }

    }

我需要应用程序在每次从另一个连接的应用程序收到消息时更改URL或路由但我无法弄清楚如何使react-router-dom(v4)在与路由器本身相同的组件中执行。任何信息或指向我的资源都将受到高度赞赏。

2 个答案:

答案 0 :(得分:3)

您需要使用React-Router中的withRouter装饰器来访问matchlocationhistory

import { withRouter } from 'react-router'

导出

时包裹您的组件
export default withRouter(yourComponent)

然后您将可以从道具中访问历史记录。

https://reacttraining.com/react-router/core/api/withRouter

答案 1 :(得分:1)

添加到andrewgi的答案:

在组件上使用withRouter()或在父组件上使用{ 在组件中尝试以下代码:

static contextTypes = {
    router: PropTypes.object,
    location: PropTypes.object
}

应定义这些,您可以尝试console.log(this.context.router, this.context.location)

然后,要以编程方式导航,请调用

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

注意:上下文API不稳定。请参阅Programmatically navigate using react routerhttps://reactjs.org/docs/context.html#why-not-to-use-context