/#/
使用 react-router 时,有什么方法可以防止在浏览器的地址栏中显示?这就是 ReactJS。即单击链接转到新路线显示localhost:3000/#/
或
localhost:3000/#/about
。视路线而定。
如何使用react-router在浏览器中停止/#/?
对于版本1,2和react,路由器3,设置URL映射方案的路线正确的方法是通过传递一个历史执行到history
的参数<Router>
。从历史文件:
简而言之,历史记录知道如何监听浏览器地址栏的变化,并将 URL 解析为一个位置对象,路由器可以使用该对象来匹配路由并呈现正确的组件集。
版本 2 和 3
在 react-router 2 和 3 中,你的路由配置代码看起来像这样:
import { browserHistory } from 'react-router'
ReactDOM.render ((
<Router history={browserHistory} >
...
</Router>
), document.body);
版本 1
在 1.x 版中,您将改为使用以下内容:
import createBrowserHistory from 'history/lib/createBrowserHistory'
ReactDOM.render ((
<Router history={createBrowserHistory()} >
...
</Router>
), document.body);
来源:2.0 版升级指南
版本 4
对于即将到来的第 4 版 react-router,语法发生了很大变化,需要BrowserRouter
用作路由器根标签。
import BrowserRouter from 'react-router/BrowserRouter'
ReactDOM.render ((
<BrowserRouter>
...
<BrowserRouter>
), document.body);
如果您不需要支持 IE8,您可以使用浏览器历史记录,而 react-router 将使用window.pushState
而不是设置哈希值。
具体如何执行取决于您使用的 React Router 版本:
- v4:https : //reacttraining.com/react-router/web/api/BrowserRouter
- v3:https : //github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md
- v2:https : //github.com/ReactTraining/react-router/blob/v2.0.0/docs/guides/Histories.md
- v1:https : //github.com/ReactTraining/react-router/blob/1.0.x/docs/guides/basics/Histories.md
您实际上可以使用 .htaccess 来完成此操作。浏览器通常需要查询字符串分隔符?
或#
确定查询字符串的开始位置和目录路径的结束位置。我们想要的最终结果是www.mysite.com/dir
所以我们需要在 Web 服务器搜索它认为我们要求的目录之前发现问题/dir
。所以我们.htaccess
在项目的根目录下放置一个文件。
# Setting up apache options
AddDefaultCharset utf-8
Options +FollowSymlinks -MultiViews -Indexes
RewriteEngine on
# Setting up apache options (Godaddy specific)
#DirectoryIndex index.php
#RewriteBase /
# Defining the rewrite rules
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^.*$ ./index.html
然后使用 window.location.pathname 获取查询参数
然后,您可以根据需要避免使用react路由,如果需要也可以操作 url 和浏览器历史记录。希望这可以帮助某人...
安装历史包
npm install history --save
接下来从历史中导入 createHistory 和 useBasename
import { createHistory, useBasename } from 'history';
...
const history = useBasename(createHistory)({
basename: '/root'
});
如果您的应用程序 url 是 www.example.com/myApp,则 /root 应该是 /myApp。
将历史变量传递给路由器
render((
<Router history={history}>
...
</Router>
), document.getElementById('example'));
现在,对于所有链接标签,在所有路径前附加一个“/”。
<Link to="/somewhere">somewhere</Link>
该解决方案的灵感来自React-Router Example, 不幸的是,在他们的 API 中没有正确记录。