Add a Trailing Slash to URL with React HashRouter

两盒软妹~` 提交于 2021-02-08 08:23:21

问题


My React app has the following render definition

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

All URLs look as such

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

I want to add a trailing slash before the # so the URLs look a little less ugly, like so

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

Any ideas on how to do so?


回答1:


You can use the following method:

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

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

Please note that I used normal Router and created browser history. Why? Cuz if I had used HashRouter it would append another # in the URL.

After this, make sure to use the base url as /admin/ everywhere else Especially when using for Redirect route inside Switch

Then add this history to the Route as follows:

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

In Switch of the Routes, you can put redirect like this:

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

Why? Because we have set the base url in createBrowserHistory as '/admin/'.

This solution works. Please try it out. Thanks




回答2:


I accomplished this by adding the following logic to my root-level parent component constructor. This component contains the Hash Router, so the constructor is called before the Hash Router is even invoked:

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+'/#');
    }
  }

... and my render:

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


来源:https://stackoverflow.com/questions/49428500/add-a-trailing-slash-to-url-with-react-hashrouter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!