小编典典

使用React Route部署到S3后看到空白页

reactjs

我用React和React
Router建立了一个SPA。我还在使用https://github.com/facebookincubator/create-react-
app,因为它是一个非常简单的应用程序。当我使用webpack开发时,我可以看到页面正常。不过,我建立生产使用后,npm run buildcreate-react- app我得到的HTML文件,CSS和JS正常。我将所有内容都上传到了S3,但是当我转到该页面时,我只会得到空白页面

这就是我所看到的

<!-- react-empty: 1 -->

我猜是这样的,因为S3默认为index.html,我无法更改。而且React
Router不知道如何处理,index.html但是我也将/root作为默认值,但是我仍然看到一个空白页面。不确定如何解决此问题?

这是我的路由器

ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Home} />
      <Route path="question2" component={Question2} />
      <Route path="question3" component={Question3} />
      <Route path="thankyou" component={Thankyou} />
    </Route>
  </Router>,
  document.getElementById('root')
);

这是模板的creawte-react-app用法,在开发中工作正常。

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <!--
      Notice the use of %PUBLIC_URL% in the tag above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start`.
      To create a production bundle, use `npm run build`.
    -->
  </body>
</html>

阅读 332

收藏
2020-07-22

共1个答案

小编典典

您正在尝试browserHistory在静态网页上使用。您应该使用hashHistory静态页面。

将浏览器历史记录用于静态页面时为什么会发生?

首次安装React Router时,它(实际上history是它使用的模块)会检查当前URL以确定初始位置。使用a
browserHistory,这是域之后的所有内容,因此其example.com/index.html初始位置为/index.html

如果您有前往的路线index.html,则该页面会在页面加载时匹配,并且看起来一切正常。如果您的应用具有<Link>/other路线的信息,您甚至可以单击它,并且URL会更改为example.com/other

但是,由于您使用的是静态网页,因此无法链接到example.com/other。如果有人尝试加载该页面,则由于服务器没有/other要服务的页面,他们将收到404错误。

输入 hashHistory

当您使用hashHistory时,确定位置时所考虑的URL的唯一部分是哈希之后的内容。

如果example.com/index.html在使用时导航到hashHistory,则会注意到URL更改为example/com/index.html#//如果网址不包含哈希,则会为您插入哈希,并将其设置为根(的绝对路径)。

让我们再回到前面的例子,其中一个<Link>链接/other,点击该链接时,URL将变更为example.com/index.html#/other。现在,如果您直接导航到该URL,则服务器将加载example.com/index.html,React
Router将检查该哈希,看是否为哈希#/other并将初始位置设置为/other路由。

2020-07-22