在使用react构建的网站中提供另一个(独立)页面或静态文件

问题描述 投票:22回答:3

我有一个使用react构建的网站,它使用react-router。对于某些路由,我想要提供另一个页面或静态文件,但由于所有请求都被转发到反应路由器,因此它不起作用。

例如

呜呜呜.没有app.com/sitemap.XML WWW.没有app.com/something.HTML

^这些链接第一次工作,但是一旦我加载网站然后它不起作用,因为所有请求通过反应路由器。

任何使其始终有效的解决方案。谢谢。

编辑

我正在使用配置为将所有请求重定向到index.html的apache服务器,我想这就是这种行为的原因。这是我的配置,但我不知道如何解决这个问题。

Options -MultiViews
RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

更新我尝试在答案中建议的解决方案

我的路线看起来像这样,对于something.html我正在加载ServerLoad组件

<Switch>
    <Route exact path="/" component={Home} />
    <Route path="/about" component={About} />
    <Route path="/about" component={About} />
    <Route path="something.html" component={ServerLoad} />
    <Route component={NoMatch} />
</Switch>

在ServerLoad组件的componentDidMount函数中,我做到了这一点。但它不起作用。

componentDidMount() {
    window.location.reload(true);
}

更多我使用create-react-app设置此项目,并通过快速服务器(like this)提供服务。我不确定我是否需要在那里进行一些设置以服务其他静态文件。

javascript apache reactjs react-router
3个回答
6
投票

这应该工作:

const reload = () => window.location.reload();

<Router>
  // all your routes..
  ...

  // Your special routes..
  <Route path="/sitemap.xml" onEnter={reload} />
  <Route path="/something.html" onEnter={reload} />
</Router>

所以,我认为这应该很清楚它的作用;)

更新:

如果这是一个选项,你可以简单地在你的<Link>中放置target =“_ blank”属性

恕我直言,这是从UX的角度来看更好,因为如果这些路由不是您的主应用程序的一部分,用户可以在访问特殊页面后切换Tab。


2
投票

这是ServiceWorker.js的一个不需要的行为,使用下面的注释并在你的React proyect的index.js中更改它,它应该工作

import { unregister } from './registerServiceWorker';
unregister();

https://github.com/facebookincubator/create-react-app/issues/2715


0
投票

使用Switch结合NoMatch组件,结合webdeb的解决方案:

<Router>
  <div>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route exact path="/admin" component={Admin} />
      <Route component={NoMatch} />
      <Route onEnter={() => window.location.reload()} />
    </Switch>
  </div>
</Router>

这将匹配路由,如果不存在有效的href则显示404,并显示文件或其他内容(如果它是有效的href)。

© www.soinside.com 2019 - 2024. All rights reserved.