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

IT技术 javascript html reactjs amazon-s3 react-router
2021-05-03 16:44:51

我用 React 和 React Router 构建了一个 SPA。我也在使用https://github.com/facebookincubator/create-react-app,因为它是一个非常简单的应用程序。当我使用 webpack 进行开发时,我可以很好地看到页面。但是,在我使用npm run buildfrom为生产构建后,我create-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>
1个回答

您正试图browserHistory在静态网页上使用 。您应该将 ahashHistory用于静态页面。

当您对静态页面使用浏览器历史记录时,为什么会发生这种情况?

当 React Router 首次挂载时,它(实际上history是它使用module)检查当前 URL 以确定初始位置。对于browserHistory,这是域之后的任何内容,因此example.com/index.html的初始位置将是/index.html.

如果您有 的路线index.html,它将在页面加载时匹配,并且事情可能看起来有效。如果您的应用程序有<Link>一个/other路线,你甚至可以点击它,这个网址被更改为example.com/other

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

进入 hashHistory

当您使用 时hashHistory,在确定位置时考虑的唯一 URL 部分是散列之后的部分。

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

回到上一个<Link>链接到 的示例/other,当单击该链接时,URL 将更改为example.com/index.html#/other现在,如果您直接导航到该 URL,服务器将加载example.com/index.html,React Router 将检查散列,查看是否存在#/other并将初始位置设置为/other路由。