将变量从自定义服务器传递到 NextJS 中的组件

IT技术 javascript reactjs next.js
2021-04-28 13:45:38

如图所示我已经建立了一个自定义的服务器NextJS这里定制路由。

服务器.js:

app.prepare()
  .then(() => {
    createServer((req, res) => {
      const parsedUrl = parse(req.url, true)
      const { pathname, query } = parsedUrl

      if (foreignLang(pathname, lang)) {
        app.render(req, res, checkLangAndConvert(links, pageVal, pathname, lang), query)
      } else {
        handle(req, res, parsedUrl)
      }
    })
      .listen(port, (err) => {
        if (err) throw err
        console.log(`> Ready on http://localhost:${port}`)
      })
  })

它基本上映射/en/url/another_urli18n。

我知道我可以query在此处使用参数并在组件中读取它,但我想将选项传递给App而不重新检查 URL。是否可以在不读取 URL 的情况下将选项从服务器级别传递到应用程序级别?

编辑:在对标记答案进行了一些调查后,解释说query实际上并不意味着 URL 中的查询参数,而不是将值从服务器传递到客户端。误导性词,因为它仅表示客户端操作。这正是我所需要的。

1个回答

这是custom-server-express的示例,它们从服务器传递id 到客户端

所以在你的情况下它会是这样的

服务器.js

const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = parse(req.url, true);
    const { pathname, query } = parsedUrl;

    if (pathname === '/pl/index') {
      app.render(req, res, '/index', { ...query, lang: 'pl' });
    } else if (pathname === '/en/index') {
      app.render(req, res, '/index', { ...query, lang: 'en' });
    } else {
      handle(req, res, parsedUrl);
    }
  }).listen(port, err => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});

页面/index.js

import React from 'react';
import { withRouter } from 'next/router';

function IndexPage(props) {
  return <h1>index lang: {props.router.query.lang}</h1>;
}

export default withRouter(IndexPage);

/pl/index将呈现index lang: pl

打算/en/index将呈现index lang: en相应

希望这可以帮助!