2016-12-13 178 views
1

我试图导航到一个路由到另一个,我设置我的路由方式方面:反应,反应路由器不确定

App.js:

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { Router, Route, IndexRoute, hashHistory } from 'react-router'; 

// Pages 
import Layout from './pages/Layout/Layout'; 
import Home from './pages/Home/Home'; 
import CityOverview from './pages/CityOverview/CityOverview'; 
import Game from './pages/Game/Game'; 

ReactDOM.render(
    <Router history={hashHistory}> 
     <Route path='/' component={Layout}> 
      <IndexRoute component={Home}></IndexRoute> 
      <Route path='/city-overview' component={CityOverview}></Route> 
      <Route path='/game' component={Game}></Route> 
     </Route> 
    </Router>, 
    document.getElementById('app') 
); 

我再尝试做导航在这个类:

import React from 'react'; 

class MyComponent extends React.Component { 

    constructor() { 
     super(); 
     this.state = { 
      email : '', 
      password : '' 
     }; 
    } 

    render() { 
     // ... 
    } 

    navigate() { 

     this.context.router.push('/city-overview'); 

    } 

} 

MyComponent.contextTypes = { 
    router: React.PropTypes.object.isRequired 
}; 

export default MyComponent; 

然而,当这个运行时,我得到一个“上下文是未定义的错误” ......

回答

1

你需要ŧ o将导航功能绑定到适当的上下文,以便其中的关键字this引用React类而不是函数。你可以使用箭头功能来做同样的事情。

navigate =() => { 

    this.context.router.push('/city-overview'); 

} 
将其绑定在构造

否则

constructor() { 
     super(); 
     this.state = { 
      email : '', 
      password : '' 
     }; 
     this.navigate = this.navigate.bind(this); 
    } 
0

使用的 “道具”,而不是 “背景”

this.props.router.push("city-overview");