代码如下:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
import './App.css';
import Header from './header';
import Main from './main';
import Footer from './footer';
import Login from './login/index'
import {
HashRouter as Router,
Route,
hashHistory,
Switch
} from 'react-router';
import { Provider} from 'react-redux'
import store from './store'
const Home = () => (
<div>
<h3>Home</h3>
</div>
)
const Chat=()=>(
<div className="App">
<Header></Header>
<Main></Main>
<Footer></Footer>
</div>
)
const LoginPage=()=>(<Login />)
class App extends Component{
render(){
**this.props.history.push('/chat')**
console.log(hashHistory)
return (
<Router history={hashHistory}>
<div style={{height:'100%'}}>
<Switch>
<Route exact path="/" component={LoginPage}/>
<Route path="/chat" component={Chat}/>
<Route path="/home" component={Home}/>
<Route path="/login" component={Login}/>
</Switch>
</div>
</Router>)
}
}
想通过render中执行切换路由this.props.history.push('/chat')报错:
TypeError: Cannot read property 'push' of undefined,不知道怎么办了,求解答
你直接:
就行了
出这个错的原因是,<Router> 组件的后代里头才有可能有
this.props.history
,而你的 App 是在 <Router> 外面的所以没有
this.props.history
,也就是this.props.history
是 undefined,所以报错:希望对你有帮助