【问题标题】:Why on react history createHashHistory appends /# for each path?为什么在反应历史 createHashHistory 上为每个路径附加 /#?
【发布时间】:2020-09-16 07:49:38
【问题描述】:

我有一个具有此配置的历史应用程序:

import { createHashHistory } from 'history';
import { ConnectedRouter } from 'connected-react-router';

const history = createHashHistory({
  hashType: 'slash',
});
    ...
  <ConnectedRouter history={history}>
    <App />
  </ConnectedRouter>

但是我所有的路线都被/#附加了 例如:localhost:8080/ 变为:localhost:8080/#/

我已经尝试将我的包更新为this question say,但没有成功。

唯一有效的方法是将createHashHistory 更改为createBrowserHistory,但我不确定它们之间有什么区别,以及为什么createHashHistory 附加/#

【问题讨论】:

  • 哈希路由一般是包含/#/的UI路由。它利用hashchangewindow.location.hash API 来模拟路由。或者,UI 路由使用 history API 更新 URL 并将以前的状态存储在浏览器内存中。

标签: javascript reactjs react-router react-router-dom history.js


【解决方案1】:

使用 hashHistory,它会产生类似的 url http://yourwebsite.net/#page/xxx

使用 browserHistory,它会产生类似的 url http://yourwebsite.net/page/xxx

使用哪一个?在现实世界的产品中,浏览器历史主要被使用。一个经验法则是“如果您使用可以处理动态 URL 的动态服务器,那么您需要使用 BrowserRouter 组件,但如果您使用的服务器仅提供静态文件,那么在这种情况下使用 HashRouter 组件。”

在您的代码中,hashType: 'slash' 只是默认值。

【讨论】:

  • 谢谢,只有一件事:hashType: 'slash' 是什么的默认值?
  • 我的意思是,你可以简单地使用 createHashHistory(),而不是 createHashHistory({ hashType: 'slash', });
猜你喜欢
  • 1970-01-01
  • 2011-02-17
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多