Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript react和react路由器上下文未定义_Javascript_Reactjs_Ecmascript 6_React Router - Fatal编程技术网

Javascript react和react路由器上下文未定义

Javascript react和react路由器上下文未定义,javascript,reactjs,ecmascript-6,react-router,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

我正在尝试从一条路线导航到另一条路线,这是我设置路线的方式:

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')
);

但是,当运行时,我得到一个“context is undefined error”…

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

navigate = () => {

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

}
或者在构造函数中绑定它

constructor () {
        super();
        this.state = {
            email : '',
            password : ''
        };
        this.navigate = this.navigate.bind(this);
    }
使用“道具”而不是“上下文”

constructor () {
        super();
        this.state = {
            email : '',
            password : ''
        };
        this.navigate = this.navigate.bind(this);
    }
this.props.router.push("city-overview");