2016-12-13 176 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");