[英]React-Router v6 not rendering in production
我在这个问题上已经没有智慧了,希望有任何想法可以让我走上正轨。
我已经实现了一个 React.js SPA,它使用react-router-dom
v6 来浏览应用程序功能。 该应用程序在我的本地主机上完美运行。 当部署到生产环境时, <Route... />
什么都不渲染。
我通过在<Routes>... </Routes>
之外呈现<h2>
元素来检查部署路径是否正确。
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
const App = () => {
const title = `${(process.env.REACT_APP_TITLE)}`;
const TwentyfourStats = () => (<h2>Works</h2>);
return (
<Router>
<div id="app" className="App">
<h2>{title}</h2>
<div>
<Routes>
<Route path="/" element={<TwentyfourStats />} />
</Routes>
</div>
</div>
</Router>
);
}
export default App;
我尝试在 package.json 中调整"homepage": "..."
时设置<Routes homebase={}>
但它没有任何区别。
非常感谢
更新:我在示例中内联了组件<TwentyfourStats />
以删除文件夹结构上的任何依赖项。 结果是一样的。
更新2:问题得到解决,正如@VitaliyRayets 所指出的那样,使用HashRouter
而不是BrowserRouter
(见答案)。
您使用使用BrowserRouter
历史 API 的 BrowserRouter。 然后你访问主页。 它不起作用,因为在生产中服务器会查找文件/
,而该文件实际上并不存在。 要解决此问题,需要配置服务器,以便为任何路由的请求提供生产版本中的index.html
文件。 如果您使用express.js
,则可以按如下方式完成。
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function(req,res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
如果您使用Nginx
。 配置:
location / {
try_files $uri $uri/ /index.html;
}
Apache
:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
除了mod_rewrite
,您还可以使用FallbackResource 。
If you haven't access to server you can use HashRouter
that uses the hash portion of the URL (ie window.location.hash
) to keep your UI in sync with the URL.
在我的反应情况下,此错误仅在我导航到带有多个斜杠的链接时发生:例如www.abc.com/Users与 apache 重写但www.abc.com/Users/email@gmail.com失败
我的解决方案是打开 index.html 并使所有链接指向主域。 例如,将<link rel="manifest" href="./manifest.json"/>
替换为<link rel="manifest" href="/manifest.json"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.