Javascript React路由器Dom(4)以编程方式导航
我正在开发一个“远程控制”的React应用程序,并试图通过Pusher连接该应用程序的选项卡导航。我正在使用react路由器dom,并在componentDidMount中设置了与Pusher的连接及其侦听的通道。我需要让应用程序在每次返回消息时更改URL导航,但无法确定“推送”消息的正确方式。我在google上搜索了很多关于以编程方式导航react router dom的线程,并尝试了这个.history.push()、这个.props.history.push(),它总是抛出一个错误,即历史未定义。侦听器与路由本身位于同一组件中Javascript React路由器Dom(4)以编程方式导航,javascript,reactjs,react-router,pusher,react-router-dom,Javascript,Reactjs,React Router,Pusher,React Router Dom,我正在开发一个“远程控制”的React应用程序,并试图通过Pusher连接该应用程序的选项卡导航。我正在使用react路由器dom,并在componentDidMount中设置了与Pusher的连接及其侦听的通道。我需要让应用程序在每次返回消息时更改URL导航,但无法确定“推送”消息的正确方式。我在google上搜索了很多关于以编程方式导航react router dom的线程,并尝试了这个.history.push()、这个.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>
)
}
}
import React,{Component}来自'React';
从“react Router dom”导入{BrowserRouter as Router,Route,Switch};
从“axios”导入axios;
从“Pusher js”导入Pusher;
从“/Component1”导入组件1;
从“/Component2”导入组件2;
导出默认类AppRouter扩展组件{
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(){
返回(
} />
} />
)
}
}
每次从另一个连接的应用程序接收到消息时,我都需要该应用程序更改URL或路由,但我不知道如何使react router dom(v4)在与路由器本身相同的组件中执行此操作。非常感谢您提供任何信息或为我指点资源。您需要使用React Router的
With Router
装饰器来访问match
、location
和history
import { withRouter } from 'react-router'
导出时包装组件
export default withRouter(yourComponent)
然后,您将可以从道具访问历史
要补充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不稳定。请参阅和。谢谢!所以我不能在拥有路由器本身的同一个组件中实现它?当我尝试使用withRouter(AppRouter)导出我的组件时,我得到了一个“你不应该在a之外使用或withRouter()”,我很乐意提供帮助。没错。它仅在组件1或组件2中使用,如示例所示。