使用 React HashRouter 向 URL 添加尾部斜杠

IT技术 reactjs react-router
2021-05-05 07:06:20

我的 React 应用程序具有以下渲染定义

ReactDOM.render(
  <Provider store={ createStoreWithMiddleware(RootReducer) }>
    <HashRouter>
        <App />
    </HashRouter>
  </Provider>,
  document.getElementById('react')
)

所有 URL 看起来都是这样

http://localhost:8080/myApp#/dashboard
http://localhost:8080/myApp#/about

我想在之前添加一个斜杠,#这样 URL 看起来那么难看,就像这样

http://localhost:8080/myApp/#/dashboard
http://localhost:8080/myApp/#/about

关于如何这样做的任何想法?

2个回答

您可以使用以下方法:

import {  Router } from "react-router-dom";
import {
    createBrowserHistory
} from 'history';

const history = createBrowserHistory({
    basename: '/admin/#/'
});

请注意,我使用了普通路由器并创建了浏览器历史记录。为什么?因为如果我使用过 HashRouter,它会在 URL 中附加另一个 #。

在此之后,请确保/admin/在其他任何地方都使用基本 url尤其是在 Switch 内部使用重定向路由时

然后将此历史记录添加到路由中,如下所示:

<Router history={history} >
  <OtherComponentsOrRoutes />
</Router>

SwitchRoutes,您可以像这样放置重定向:

<Route exact path="/admin/" render={() => (<Redirect to="/dashboard" />)} />

为什么?因为我们已经将 createBrowserHistory 中的基本 url 设置为“/admin/”。

此解决方案有效。请尝试一下。谢谢

我通过将以下逻辑添加到我的根级父组件构造函数来完成此操作。该组件包含哈希路由器,因此在调用哈希路由器之前会调用构造函数:

const history = require('myHistory');
const {HashRouter, Route, Switch} = require('react-router-dom');

...

  constructor(props) {
    super(props);
    if(document.location.pathname[document.location.pathname.length-1] !== '/') {
      // kinda hacky way to get the sexy /#/ url instead of just #/
      history.replace(document.location.pathname+'/#');
    }
  }

...和我的渲染:

render() {
    return (
      <HashRouter history={history}>
        <div>
          <Switch>
            ...
          </Switch>
        </div>
      </HashRouter>
    );
  }