反应和反应 - 路由器上下文未定义

时间:2016-12-13 08:55:04

标签: javascript reactjs ecmascript-6 react-router

我尝试从一条路线导航到另一条路线,就像我设置路线一样:

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;

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

2 个答案:

答案 0 :(得分:1)

您需要将导航功能绑定到适当的上下文,以便其中的this关键字引用React类而不是函数。您可以使用箭头函数来执行相同的操作。

navigate = () => {

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

}

或者在构造函数

中绑定它
constructor () {
        super();
        this.state = {
            email : '',
            password : ''
        };
        this.navigate = this.navigate.bind(this);
    }

答案 1 :(得分:0)

使用&#34;道具&#34;而不是&#34; context&#34;

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