NodeJS 在react中处理水合和服务器端渲染时出现问题

agxfikkp  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(181)

我一直在尝试使用SSR与React,但我坚持与此错误enter image description here此外,缩小React错误是enter image description here
我的服务器端代码server.js

import express from "express";
import React from "react";
import fs from "fs"
import path from "path";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import App from "../App";

const app = express()

const context = {}

app.get("^/$", (req, res) => {
    fs.readFile(path.resolve('./build/index.html'), 'utf-8', (err, data) => {
        if (err) {
            console.error(err)
            return res.status(500).send('some error occured')
        }
        const html = ReactDOMServer.renderToString(
            <StaticRouter context={context}>
                <App />
            </StaticRouter>
        )
        return res.send(data.replace(`<div id="root"></div>`, `<div id="root">${html}</div>`))
    })
})

app.use(express.static(path.resolve(__dirname + "../../../build/")));

app.listen(4000, () => {
    console.log("4000")
})

我用react搜索了SSR,但没有找到对我有用的。此外,我无法检测到错误

mpbci0fu

mpbci0fu1#

请将错误信息粘贴到内容中好吗?作为良好实践的一部分,建议复制并粘贴您收到的错误消息,而不是上传图像。:)
关于你的代码,我相信它会导致一个水合错误,因为你试图执行包含客户端特定代码的react组件的服务器端渲染。您正在使用ReactDOMServer.renderToStringApp组件呈现为服务器端的字符串。但是,如果App组件包含客户端特定的代码,例如事件处理程序或浏览器API,则这些代码与服务器端渲染不兼容,因此会导致错误。
因此,您必须确保App组件及其依赖项与服务器端呈现兼容。但这是一种直觉,我不能告诉没有看到你的代码休息

相关问题