6

我的应用程序有一个简单的 ssr 路由,下面是我的代码

索引.tsx

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.min.css";

ReactDOM.hydrate(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);
serviceWorker.unregister();

应用程序.tsx

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
} from "react-router-dom";
import Home from "./components/home/Home";
import Tournament from "./components/tournament/Tournament";
import "./App.css";

function App() {
  return (
    <div className="App">
      <Router>
        <Switch>
          <Route path="/" exact strict component={Home} />
          <Route
            path="/tournament/:tourId/:tourName"
            exact
            component={Tournament}
          />
          <Redirect from="*" to={"/"} />
        </Switch>
      </Router>
    </div>
  );
}

export default App;

服务器/server.js

import path from "path";
import fs from "fs";

import express from "express";
import React from "react";
import ReactDOMServer from "react-dom/server";

import App from "../src/App";

const PORT = 8000;
const app = express();

const router = express.Router();

app.get("/*", (req, res) => {
  const context = {};
  const app = ReactDOMServer.renderToString(
    <App />
  );

  const indexFile = path.resolve("./build/index.html");
  fs.readFile(indexFile, "utf8", (err, data) => {
    if (err) {
      console.error("Something went wrong:", err);
      return res.status(500).send("Oops, better luck next time!");
    }

    return res.send(
      data.replace('<div id="root"></div>', `<div id="root">${app}</div>`)
    );
  });
});

router.use(
  express.static(path.resolve(__dirname, "..", "build"), { maxAge: "30d" })
);

// tell the app to use the above rules
app.use(router);

app.use(express.static("./build"));
app.listen(PORT, () => {
  console.log(`SSR running on port ${PORT}`);
});

服务器/index.js

require("ignore-styles");

require("@babel/register")({
  ignore: [/(node_modules)/],
  presets: ["@babel/preset-env", "@babel/preset-react"],
});

require("./server");

当我运行node server/index.js时,它会启动服务器,这很好。但是当我在浏览器上启动http://localhost:8000/时,它给了我以下错误

警告:React.createElement:类型无效——需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:对象。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

错误:元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。在 ReactDOMServerRenderer.render ...

PS:我是 reactjs 新手

4

1 回答 1

0
ReactDOMServer.renderToString(
    <App />
  );

如果您查看“react-dom/server”文档,您可以使用不同的方法。有时“.renderToString”在服务器上不起作用,所以使用另一个像:

.renderToStaticMarkup()
.renderToNodeStream()
.renderToStaticNodeStream() 
于 2021-12-23T08:20:19.783 回答