Javascript react和react路由器上下文未定义
我正在尝试从一条路线导航到另一条路线,这是我设置路线的方式: App.js: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
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");