簡體   English   中英

運行構建時反應路由器動態網址不起作用

[英]react router dynamic urls not working when running build

使用 react 的 create-react-app 版本。

當我在瀏覽器中運行構建文件夾時,React-router-dom 停止為動態 url 正常運行。

它工作正常,但是當從 react-scripts 開始運行時

import { BrowserRouter as Router, Route } from 'react-router-dom'

      <Route path="/" component={Home} exact />
      <Route path="/blog/" component={Blog} exact />
      <Route path="/blog/:id" component={BlogPost} />
      <Route path="/portfolio/:id" component={PortfolioItem} />
      <Route path="/portfolio" component={Portfolio} exact />
      <Route path="/about" component={About} exact />
      <Route path="/services/:id" component={Service} />


/blog/:id 和 /services/:id 都給出 404 所有其他路由正常工作 100%,fetch 正在處理我的 api 內容,圖像顯示,一切都在靜態 url 上工作。

重復這僅在運行構建時發生。

將文件命名為“.htaccess”並將其放入其中:

  <IfModule mod_rewrite.c>
   RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
  </IfModule>

如果它再次不起作用,請檢查您的 package.json 以將主頁屬性設置為您的主網址。

編輯:既然你澄清你正在運行一個 HTTP 服務器,我已經刪除了我的舊答案並添加了一個替代方案:

問題很可能是您的 Apache 服務器的設置。 您可以嘗試使用哈希歷史記錄,如果可行,我們將確定問題出在 Apache 上:

import { createHashHistory } from "history"
import { Route, Router, Switch } from "react-router-dom"

const customHistory = createHashHistory()

...

<Router history={customHistory}>
  <Switch>
    <Route path="/" component={Home} exact />
    <Route path="/blog/" component={Blog} exact />
    <Route path="/blog/:id" component={BlogPost} />
    <Route path="/portfolio/:id" component={PortfolioItem} />
    <Route path="/portfolio" component={Portfolio} exact />
    <Route path="/about" component={About} exact />
    <Route path="/services/:id" component={Service} />
  </Switch>
</Router>

注意:如果這樣做有效但您不想使用哈希歷史記錄,則必須將 Apache 服務器正確設置為反向代理。 可在此處閱讀相關說明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM