我正在开发一个“远程控制”的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 回答
您需要使用React-Router中的
withRouter
装饰器来访问match
,location
和history
.导出时包裹您的组件
然后您将可以从道具访问历史记录 .
https://reacttraining.com/react-router/core/api/withRouter
添加到andrewgi的答案:
在组件上使用
withRouter()
或在父组件上使用后,请在组件中尝试以下代码:这些应该定义,你可以尝试
console.log(this.context.router, this.context.location)
然后,以编程方式导航,调用
this.context.router.history.push('/someRoute');
注意:上下文API不稳定 . 见Programmatically navigate using react router和https://reactjs.org/docs/context.html#why-not-to-use-context .