react-router是v4版本,程式碼如下
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Redirect, withRouter } from 'react-router-dom';
import './index.less';
import Work from './index/work';
import Info from './index/info';
class Index extends Component {
constructor(props) {
super(props);
}
handleRouterPush(path, e) {
this.props.history.push(path);
}
render() {
return (
<p>
<Router>
<p>
<Switch>
<Route exact path="/index">
<Redirect from="/index" to="/index/work" />
</Route>
<Route path="/index/work" component={ Work } />
<Route path="/index/info" component={ Info } />
</Switch>
<p className="index-bottom">
<p onClick={ this.handleRouterPush.bind(this, '/index/work') }>
<p className="index-bottom-icon">
<span>工作</span>
</p>
</p>
<p onClick={ this.handleRouterPush.bind(this, '/index/info') }>
<p className="index-bottom-icon">
<span>个人</span>
</p>
</p>
</p>
</p>
</Router>
</p>
);
}
}
export default withRouter(Index);
若是改成使用Link跳轉則是可以的,但是this.props.history.push就不行了,請問這是為什麼?
世界只因有你2017-06-26 11:00:01
我解決了。因為這個元件是在App.js中的Route載入的,我在App.js裡面也使用了Router元件,似乎再在index.js裡面使用Router元件就重複了。我把index.js裡面的Router刪了就好了
巴扎黑2017-06-26 11:00:01
<Switch>
<Route exact path="/index">
<Redirect from="/index" to="/index/work" />
</Route>
<Route **exact** path="/index/work" component={ Work } />
<Route **exact** path="/index/info" component={ Info } />
</Switch>
試試