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 (
            <div>
                <Router>
                    <div>
                        <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>
                        <div className="index-bottom">
                            <div onClick={ this.handleRouterPush.bind(this, '/index/work') }>
                                <div className="index-bottom-icon">
                                    <span>工作</span>
                                </div>
                            </div>
                            <div onClick={ this.handleRouterPush.bind(this, '/index/info') }>
                                <div className="index-bottom-icon">
                                    <span>个人</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </Router>
            </div>
        );
    }
}

export default withRouter(Index);

若是改成使用Link跳转则是可以的,但是this.props.history.push就不行了,请问这是为什么?

阅读 19.8k
2 个回答

我解决了。因为这个组件是在App.js中的Route加载的,我在App.js里面也使用了Router组件,似乎再在index.js里面使用Router组件就重复了。我把index.js里面的Router删了就好了

<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>

试试

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题