Den*_*ush 24 reactjs react-router
我正在使用react-router进行路由,我使用hashHistory选项,以便我可以从浏览器刷新页面或指定我现有路由的URL并登陆到右侧页面.它工作正常,但我看到网址中的哈希是这样的: http:// localhost /#/ login?_k = ya6z6i
这是我的路由配置:
ReactDOM.render((
<Router history={hashHistory}>
<Route path='/' component={MasterPage}>
<IndexRoute component={LoginPage} />
<Route path='/search' component={SearchPage} />
<Route path='/login' component={LoginPage} />
<Route path='/payment' component={PaymentPage} />
</Route>
</Router>),
document.getElementById('app-container'));
Run Code Online (Sandbox Code Playgroud)
Aal*_*eks 25
您是否尝试过browserHistory选项?您还可以从浏览器刷新页面或指定其中一条现有路线的URL并登陆右侧页面.
import { Router, Route, browserHistory } from 'react-router';
ReactDOM.render((
<Router history={browserHistory}>
<Route path='/' component={MasterPage}>
<IndexRoute component={LoginPage} />
<Route path='/search' component={SearchPage} />
<Route path='/login' component={LoginPage} />
<Route path='/payment' component={PaymentPage} />
</Route>
</Router>),
document.getElementById('app-container'));
Run Code Online (Sandbox Code Playgroud)
而且考虑到react-router github doc,hashHistory不用于生产用途.
https://github.com/ReactTraining/react-router/blob/master/docs/guides/Histories.md#browserhistory
我应该使用hashHistory吗?
哈希历史记录无需配置您的服务器即可运行,因此如果您刚刚开始使用,请继续使用它.但是,我们不建议在生产中使用它,每个Web应用程序都应该立即使用browserHistory
小智 5
我是新来的反应者,但我使用过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")
);
Run Code Online (Sandbox Code Playgroud)
小智 5
我相信 Dennis Nerush 上面提到过,您需要使用 {browserHistory} 而不是 {hashHistory},但是要使相同的页面呈现正常工作,您需要对服务器进行一些配置以允许这样做。
根据您的托管位置或您使用的服务器,有几种方法可以执行此操作
对于Apache,您必须将以下内容添加到 .htaccess(或创建 .htaccess 并将其放置在网站的根文件夹中):
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
Run Code Online (Sandbox Code Playgroud)
对于 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)
}
})
})
Run Code Online (Sandbox Code Playgroud)
对于 Nginx 服务器,您需要将以下内容添加到 Nginx.conf 文件中
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.html break;
}
}
Run Code Online (Sandbox Code Playgroud)
对于 Amplify,您需要转到重写和重定向并添加包含以下信息的新规则(注意我仅在 AWS 上使用过此规则):
Source address: </^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf)$)([^.]+$)/>
Target address: /index.html
Type: 200
Run Code Online (Sandbox Code Playgroud)
如果您想对这个主题进行更多研究,这里有一些链接。
https://www.andreasreiterer.at/fix-browserrouter-on-apache/#comment-186(专门针对 Apache)
https://ui.dev/react-router-cannot-get-url-refresh/(针对不同服务器或没有我上面未添加的服务器的多种方法)
React Router DOM 在 Amplify 控制台 AWS 上无法正常工作(将此控制台用于 AWS 和 Amplify)
| 归档时间: |
|
| 查看次数: |
36756 次 |
| 最近记录: |