gpt4 book ai didi

reactjs - React Context 不适用于服务器端渲染

转载 作者:行者123 更新时间:2023-12-03 16:39:19 24 4
gpt4 key购买 nike

我正在尝试使用 SSR 获得 react 上下文。这就是我所拥有的

// server/index.s

import express from "express";
import serverRenderer from "./middleware/renderer";
const PORT = 3000;
const path = require("path");
const app = express();
const router = express.Router();
router.use("^/$", serverRenderer);

app.use(router);
app.listen(PORT, error => {
console.log("listening on 3000 from the server");
if (error) {
console.log(error);
}
});

这就是渲染器的样子——
export default (req, res, next) => {
const filePath = path.resolve(__dirname, "..", "..", "..", "index.html");
fs.readFile(filePath, "utf8", (err, htmlData) => {
if (err) {
console.log("err", err);
return res.status(404).end();
}
const store = configureStore();
store.dispatch(getDesktopFooter(`${req.url}`)).then(data => {
const preloadedState = store.getState();
const TestContext = React.createContext({
hello: "hello"
});
const renderedBody = ReactDOMServer.renderToStaticMarkup(
<TestContext.Provider value={{ hello: "hello" }}>
<DummyApp />
</TestContext.Provider>
);

// const renderedBody = "";
//render the app as a string
const helmet = Helmet.renderStatic();

//inject the rendered app into our html and send it
// Form the final HTML response
const html = prepHTML(htmlData, {
html: helmet.htmlAttributes.toString(),
head:
helmet.title.toString() +
helmet.meta.toString() +
helmet.link.toString(),
body: renderedBody,
preloadedState: preloadedState
});

// Up, up, and away...
return res.send(html);
});
});
};

我的 DummyApp 看起来像
import React from "react";
import Test from "./Test";
import { default as AppStyles } from "./App.css";
export default class DummyApp extends React.Component {
render() {
console.log("DUMMY APP CONTEXT");
console.log(this.context);
return (
<React.Fragment>
<div className={AppStyles.base}>
<Test />
</div>
</React.Fragment>
);
}
}

上下文总是 {} ,什么时候应该是 {hello: "hello"}
为什么会这样?

最佳答案

您需要在组件中使用上下文才能读取它。

您还需要创建 TestContext在服务器渲染功能之外,以便您的组件可以导入并使用它。

示例

// TestContext.js
export default TestContext = React.createContext({
hello: "hello"
});

// server.js
const TestContext = require("./TestContext.js")

export default (req, res, next) => {
// ...
const renderedBody = ReactDOMServer.renderToStaticMarkup(
<TestContext.Provider value={{ hello: "hello" }}>
<DummyApp />
</TestContext.Provider>
);
// ...
};

// DummyApp.js
import TestContext from "./TestContext.js";

export default class DummyApp extends React.Component {
static contextType = TestContext;

render() {
console.log(this.context);
return (
<React.Fragment>
<div className={AppStyles.base}>
<Test />
</div>
</React.Fragment>
);
}
}

关于reactjs - React Context 不适用于服务器端渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55158168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com