【问题标题】:How to run "index.html" in React如何在 React 中运行“index.html”
【发布时间】:2021-02-05 03:02:09
【问题描述】:

我正在通过将构建文件放在服务器上来测试它。

但是,如果我直接在 URL 的末尾键入 index.html,我会得到一个灰屏。是什么原因?

[示例]

baseURL/ -> 工作

baseURL/index.html -> 不工作

【问题讨论】:

  • 您使用的是哪个服务器?如果 IIS 使用 web.config,apache 和 nginx 使用 .htaccess
  • 我没有使用本地服务器。我正在使用 filezilla 的内部服务器进行测试。你知道为什么访问 index.html 时不知道吗?
  • 如果IIS使用web.config,apache和nginx使用.htaccess,修改这个
  • 不能通过修改React构建文件或者项目文件来解决吗?
  • 绝对不!正如我之前所说,你明白了吗?

标签: html reactjs server build


【解决方案1】:

这样想:

当您访问 index.html 时 - 您将像访问硬盘上的文件一样访问它。没有魔法 - 你得到 index.html 的文字内容 - 这是一个空页面。

当您访问路由时,奇迹发生了 - 实际代码执行,服务器上的路由被触发 - 您的空视图被您的浏览器可以理解的代码填充并创建一个完整的工作页面。

这样做的缺点是页面的 SEO。谷歌搜索机器人在推广未针对 SEO 反应应用程序进行优化时会遇到问题 - 为此您必须使用 ReactDOMServer 或其他变体。

【讨论】:

    【解决方案2】:

    浏览到 baseURL/index.html 会呈现一个空的 <div>

    默认情况下,CRA 构建 index.html,没有可见的 <body> 内容。它只包含一个空的“根”div。这是代码:

      <body>
        <noscript>You need to enable JavaScript to run this app.</noscript>
        <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` or `yarn start`.
          To create a production bundle, use `npm run build` or `yarn build`.
        -->
      </body>
    

    直接浏览到index.html 会呈现该页面,显示空 div。这就是为什么您什么也看不到,或者说“灰屏”。

    浏览到 baseURL 允许 React 运行。

    浏览 React 项目的 baseURL 可以让 React 的魔法发挥作用。文件index.js 被处理,React 将你的&lt;App /&gt; 组件插入到index.html 的空“根” div 中。

    React render 函数执行此任务。

    ReactDOM.render() 函数有两个参数,HTML 代码和一个 HTML 元素。该函数的目的是显示指定的 指定 HTML 元素内的 HTML 代码。

    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById('root')
    );
    

    在上面的render 函数中,第一个参数(&lt;App /&gt; 组件的输出)插入到第二个参数(index.html 中的“根”div)中标识的元素中。结果,浏览器会显示您的应用程序输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2020-06-12
      • 2013-11-14
      • 1970-01-01
      • 2014-04-02
      • 2020-06-24
      • 2018-11-19
      相关资源
      最近更新 更多