使用 React HashRouter 向 URL 添加尾部斜杠 [英] Add a Trailing Slash to URL with React HashRouter

查看:41
本文介绍了使用 React HashRouter 向 URL 添加尾部斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

ReactDOM.render(<Provider store={ createStoreWithMiddleware(RootReducer) }><HashRouter><应用程序/></HashRouter></提供者>,document.getElementById('react'))

所有网址看起来都是这样

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

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

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

关于如何做到这一点的任何想法?

解决方案

我通过将以下逻辑添加到我的根级父组件构造函数来实现这一点.该组件包含哈希路由器,因此在调用哈希路由器之前会调用构造函数:

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

...

 构造函数(道具){超级(道具);if(document.location.pathname[document.location.pathname.length-1] !== '/') {//获取性感的/#/url 而不仅仅是 #/history.replace(document.location.pathname+'/#');}}

...和我的渲染:

render() {返回 (<HashRouter history={history}><div><开关>...</开关>

</HashRouter>);}

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?

解决方案

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

这篇关于使用 React HashRouter 向 URL 添加尾部斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆