首页 > 解决方案 > React 正在使用占位符标记覆盖服务器端呈现的页面

问题描述

我目前正在使用 React 和 SSR 设置应用程序。由于此问题范围之外的原因,我无法使用 Next.js、Gatsby 甚至 Create React App 等框架。

Web 服务器是用 NestJS 编写的,这就是我用来处理路由/请求的东西。到目前为止,我要做的是将所有请求发送到“Catch-all”处理程序,该处理程序将 URL 映射到写入 MDX 文件的内容,将 MDX 转换为 JSX,并将 JSX 与非常基本的 HTML 连接起来加载 React 的模板。这就是问题发生的地方。一旦我将 HTML 从 NestJS 发送到浏览器,bundle.js文件就会启动并覆盖我发送它的 JSX 内容。基本上我的问题是如何防止这种行为?

在反应方面,我有一个非常基本的设置:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>React</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
// index.js

import React from "react";
import { hydrate } from "react-dom";

import App from "./App";
import "./styles.css";

hydrate(<App />, document.getElementById("root"));
// App.jsx
import React from "react";

const App = () => {
  return (
    <nav>
      <ul>
        <li>
          <a href="/">Home</a>
        </li>
      </ul>
    </nav>
  );
};

export default App;

在 NestJS 方面,基本上我的 Catch-All 控制器是这样做的:

  @Get('*')
  async getOne(@Req() req: Request): Promise<string> {
    const { url } = req;

    // this reads the file based on the URL, and transpiles MDX -> JSX -> HTML
    const content = await this.webClientService.getContentByURL(url);
    const jsx = await mdx(content);
    const mdxToString = ReactDOMServer.renderToStaticMarkup(jsx);

    // this reads the output HTML of my react application
    const app = await this.webClientService.getApp();

    // this replaces the empty react content, with my content.
    const output = app
      .replace('bundle.js', '/bundle.js')
      .replace('<div id="root"></div>', `<div id="root">${mdxToString}</div>`);

    return output;
  }

所有这些都可以正常工作,但是当我运行代码时,会发生以下情况:

React 覆盖组件

有什么办法可以防止这种行为?

标签: reactjsnestjsserver-side-rendering

解决方案


在不了解您的服务器端代码的情况下,您在客户端的入口点通常会从变量中读取初始状态并重新水化。你index.js似乎没有这样做。

有很多关于如何做到这一点的例子,但我认为这是你的问题。


推荐阅读