问题
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