如何从react-router中的url中删除哈希值

时间:2016-02-03 16:09:10

标签: reactjs react-router

我使用react-router进行路由,然后使用hashHistory选项,以便我可以从浏览器刷新页面或指定我现有路线的URL并登陆到右侧页面。 它工作正常,但我在网址中看到这样的哈希: http://localhost/#/login?_k=ya6z6i

这是我的路由配置:

*.tsx

5 个答案:

答案 0 :(得分:23)

您是否尝试过browserHistory选项?您还可以从浏览器刷新页面或指定其中一条现有路线的网址并登陆右侧页面。

* 13,14,15,16,17,18,19,20 * * 3

此外,考虑到react-router github doc,hashHistory不适合生产使用。

https://github.com/ReactTraining/react-router/blob/master/docs/guides/Histories.md#browserhistory

我应该使用hashHistory吗?

  

哈希历史记录无需配置您的服务器即可运行,因此,如果您只是   入门,继续使用它。但是,我们不建议使用它   在制作中,每个网络应用都应该立志使用browserHistory

答案 1 :(得分:3)

您需要从browserHistory中导入react-router 并将其传递给<Router />,以便从URL中删除哈希

例如:

import { browserHistory } from 'react-router';

<Router history={browserHistory}>
 //Place your route here
</Router>

答案 2 :(得分:3)

我是新手做出反应,但我使用过BrowserRouter,它运行正常: -

    import React from "react";
    import ReactDOM from "react-dom";
    import { BrowserRouter, Route, Switch } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter >
    <Switch>
      {indexRoutes.map((prop, key) => {
        return <Route to={prop.path} component={prop.component} key={key} />;
      })}
    </Switch>
  </BrowserRouter>,
  document.getElementById("root")
);

答案 3 :(得分:0)

试试这个:

// v1.x
import createBrowserHistory from 'history/lib/createBrowserHistory'
<Router history={createBrowserHistory()} />

// v2.0.0
import { browserHistory } from 'react-router'
<Router history={browserHistory} />


const history = createHashHistory({ queryKey: false });
<Router history={history}>
</Router>

https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#using-custom-histories

https://github.com/reactjs/react-router/blob/8ef625e8fa7c41dda0f3d1d68a10b74bd93a4101/docs/guides/ba...

答案 4 :(得分:0)

我相信Dennis Nerush前面已经提到过,您需要使用{browserHistory}而不是{hashHistory},但是要使同一页面呈现正常工作,您需要对服务器进行一些配置以实现此目的。

根据托管位置或使用的服务器,有几种方法可以做到这一点

对于 Apache ,您必须将以下内容添加到.htaccess中(或创建.htaccess并将其放置在网站的根文件夹中):

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

对于Node.js / Express,您需要添加以下代码:

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) {
    if (err) {
      res.status(500).send(err)
    }
  })
})

对于Nginx服务器,您需要将以下内容添加到Nginx.conf文件中

location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /index.html break;
  }
}

对于Amplify,您需要转到Rewrites&Redirects并添加一条包含以下信息的新规则(注意,我仅在AWS上使用过此规则):

Source address: </^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf)$)([^.]+$)/>
Target address: /index.html
Type: 200

如果您想对该主题进行更多研究,请点击以下链接。

https://www.andreasreiterer.at/fix-browserrouter-on-apache/#comment-186(专用于Apache)

https://ui.dev/react-router-cannot-get-url-refresh/(用于不同服务器的多种方法,或者没有在上面未添加的服务器)

React Router DOM not working correctly on Amplify Console AWS(将此用于AWS和Amplify)