[英]React Router doesn't render components after build to ftp server
我用yarn build
了 React 应用程序。 为了让应用程序在我的服务器上运行,我将"homepage": "./"
添加到 package.json 文件中。 该应用程序存储在服务器上的一个文件夹中,我使用https://my-url.com/appname访问该应用程序
App.js 已呈现,但我没有看到我的组件:
function App() {
const [navigationState, setNavigationState] = useState(false);
return (
<div className="App">
<Router>
<Header
showNavigation={navigationState}
setShowNavigation={setNavigationState}
/>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/contact" exact component={Contact} />
</Switch>
<Footer />
</Router>
<div className="space"></div>
</div>
);
}
在Header
组件中,我有类似的链接
<Link to="/">Home</Link>
<Link to ="/contact">Contact</Link>
当我单击Home
时,URL 切换到https://my-url.com/ ,我看到了 Home 组件。 单击“ Contact
”后,URL 切换到https://my-url.com/contact ,我看到了联系人。
我的 .htaccess 看起来像:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
我需要做什么才能保留文件夹路径并在第一次调用时呈现主组件?
404
404
404
单击主页链接后,我得到 -https://my-url.com/ 显示主页组件单击联系人链接后,我得到https://my-url.com/contact显示联系人组件
重新加载两个网址上的页面都会出现404
。
这是我的package.json
:
{
"name": "appname",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
},
"scripts": {
"start": "BROWSER=firefox PORT=2000 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"homepage": "./"
}
我在之前的项目中遇到了这个问题,因为它是带有 apache 的 GoDaddy Linux 主机,所以我添加了这一行
"homepage": "my-url.com" 到你的 package.json
然后我编辑了我的 .htaccess 文件,在它上面添加了我的主要路由
我使用的文件有这个内容
RewriteOptions inherit
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . / [L]
我认为这可能与 react-router 通过客户端或服务器端渲染 (SSR) 处理渲染的方式有关。 请检查此文档片段以正确设置客户端https://create-react-app.dev/docs/deployment/#serving-apps-with-client-side-routing
或者尝试将渲染的配置更改为SSR,应该没问题。
为了让它工作,我做了以下步骤:
.htaccess
文件添加到public
文件夹:Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
package.json
并添加:"homepage": "http://my-url.com/foldername"
App.js
将文件夹名称添加到<Route path="<<here>>" />
:<Route path="/foldername/" exact component={Home} />
<Route path="/foldername/contact" exact component={Contact} />
对我来说同样的问题,我不得不将 App.jsx BrowserRouter 切换到 HashRouter(我的 ftp 不处理 BrowserRouter),并且在一切正常之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.