javascript - React-router中的this.props.history.push,url發生了變化,但是頁面沒有變化
問題描述
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就不行了,請問這是為什么?
問題解答
回答1:我解決了。因為這個組件是在App.js中的Route加載的,我在App.js里面也使用了Router組件,似乎再在index.js里面使用Router組件就重復了。我把index.js里面的Router刪了就好了
回答2:<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>
試試
