[英]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.