如果您在v4之前使用了react router,那么您的代码看起来是正确的,但是react-router
v4在整个代码库中都有重大更改,包括服务器渲染方法。在v4中,有一个专门用于服务器渲染的新组件-
StaticRouter。
您的代码在v4中应如下所示:
import path from "path";import { Server } from "http";import Express from "express";import React from "react";import { renderToString } from "react-dom/server";import { StaticRouter } from "react-router";import App from "./app";import NotFoundPage from "./components/NotFoundPage";// Initialize the express server, and tell it to use ejsconst app = new Express();const server = new Server(app);app.set("view engine", "ejs");app.set("views", path.join(__dirname, "views"));// Tell express where the static assets areapp.use(Express.static(path.join(__dirname, "static")));app.get("*", (req, res) => { // This context object contains the results of the render const context = {}; const html = renderToString( <StaticRouter location={req.url} context={context}> <App /> </StaticRouter> ); res.status(200).send(html);});const port = process.env.PORT || 3000;const env = process.env.NODE_ENV || "production";server.listen(port, err => { if (err) { return console.error(err); } console.info(`Server running on http://localhost:${port} [${env}]`);});这是EbayTech的一篇非常好的带注释的文章,显示了如何使用StaticRouter(用于服务器)和BrowserRouter(用于客户端)设置应用程序



