消息关闭
    暂无新消息!

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就不行了,请问这是为什么?


2个回答

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

试试

︿ 0

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