首页 > 解决方案 > 使用 HashRouter 时以编程方式导航

问题描述

我在 react.js 应用程序中将 HashRouter 用于我的路由。然后我有一个执行以下操作的函数:

this.props.history.push('/somePath');

问题是,自从我开始使用 以来HashRouter,当调用该函数时,页面并没有推送到该路径。

我登录了this.props.history,并且push在那里。

如何在使用时以编程方式导航HashRouter

注:我用过withRouter

这是代码:

import React, { Component } from 'react';
import { HashRouter, Route, Switch, Redirect, withRouter } from 'react-router-dom';
// Other imports

class App extends Component {
    navigate = () => {
        this.props.history.push('/route1');
        console.log(this.props.history);
    };

    render() {    
        return (
            <div className="App">
                <Header />

                <HashRouter>
                    <Switch>
                        <Route
                            path="/route1"
                            exact
                            render={() => (
                                <FirstRoute someSetting='setting1'/>
                            )}
                        />
                        <Route
                            path="/route2"
                            exact
                            render={() => (
                                <SecondRoute anotherSetting='Really Cool'/>
                            )}
                        />
                        <Route path="/404" component={NotFound} />
                        <Route exact path="/" render={() => <HomePage someSettings='Home Page' />} />
                        <Redirect to="/404" />
                    </Switch>
                </HashRouter>

                <BottomBar />
            </div>
        );
    }
}

export default withRouter(App);

标签: javascriptreactjsreact-router

解决方案


推荐阅读