reactjs - Fastify 使用 next.js 为渲染提供 react 属性
问题描述
我正在使用 Next.js 的示例服务器和 Fastify 并对其进行试验,我想知道是否有一种方法可以将 JSON 对象作为道具传递给渲染?我试图在文档中找到任何东西,但找不到任何东西。
我正在使用的服务器代码是这样的,
const fastify = require('fastify')();
const Next = require('next');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
fastify.register((fastify, opts, next) => {
const app = Next({ dev })
app.prepare().then(() => {
fastify.get('/', (req, res) => {
let object = {"hello": "world"}; // object I want to pass as a prop
return app.render(req.req, res.res, '/index', req.query).then(() => {
res.sent = true
})
})
next()
}).catch(err => next(err))
})
fastify.listen(port, err => {
if (err) throw err
console.log(`Ready on http://localhost:${port}`)
})
解决方案
您的问题不是特定于Fastify
,而是与所有服务器框架相关。
基本思想是将req
&res
对象传递给 Next 的getInitialProps
。
所以你可以把你的数据放在他们身上。
例如,express 的 Response 对象具有locals
特定于该作业的属性。
因此,为了传递数据,请将其附加到 req/res。
fastify.get('/', (req, res) => {
const object = { hello: 'world' }; // object I want to pass as a prop
res.res.myDataFromController = object;
return app.render(req.req, res.res, '/index', req.query).then(() => {
res.sent = true;
});
});
// some next page.jsx
const IndexPage = ({ dataFromGetInitilProps }) => (
<div> {JSON.stringify(dataFromGetInitilProps, null, 2)} </div>
);
IndexPage.getInitilProps = ctx => {
const { res } = ctx;
// res will be on the context only in server-side
const dataFromGetInitilProps = res ? res.myDataFromController: null;
return {
dataFromGetInitilProps: res.myDataFromController,
};
};
export default IndexPage;
推荐阅读
- javascript - 更改猫头鹰转马时间
- python - 如何让 Python Infinite while / else 语句中断?
- ruby-on-rails - 无法在 Bigsur 上安装 mysql2 Gem
- selenium-chromedriver - 如何为具有相同名称的多个输入设置值?
- c# - 使用图像而不是文本的 Visual Studio 注释
- javascript - 在多个值的对象数组中搜索
- php - Symfony 表单类型从另一个实体添加查询构建器
- javascript - 两个 Angular 应用程序之间的通信
- oauth-2.0 - 用于 Rest API 的 Openid 连接/Oauth2
- c# - 订单完成后如何从数据库中扣除产品数量