javascript - this.props.history.push in React-router, the url has changed, but the page has not changed
高洛峰
高洛峰 2017-06-26 10:58:01
0
2
845

react-router is the v4 version, the code is as follows

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

If you change it to use Link to jump, it will work, but this.props.history.push will not work. Why is this?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
世界只因有你

I solved it. Because this component is loaded in Route in App.js, and I also use the Router component in App.js, it seems that it will be duplicated if I use the Router component in index.js. I just delete the Router in index.js and it will be fine

巴扎黑
<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>

Try it

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template