首页 > 解决方案 > 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}`)
})

标签: reactjsnext.jsfastify

解决方案


您的问题不是特定于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;

推荐阅读