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

2024-02-18

我已经在 NextJS 中设置了一个自定义服务器,如图所示here https://github.com/zeit/next.js/#custom-server-and-routing用于自定义路由。

服务器.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 to /another_url对于国际化。

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

Edit:经过一番调查后,标记的答案解释说query实际上并不是指URL中的查询参数,而是从服务器向客户端传递一个值。误导性词语,因为它仅表示客户端操作。这正是我所需要的。


这是一个例子定制服务器快递 https://github.com/zeit/next.js/blob/85769c3d3296cdcddc0fb36f05058c8e451ca57f/examples/custom-server-express/他们经过的地方id 从服务器端到客户端 https://github.com/zeit/next.js/blob/85769c3d3296cdcddc0fb36f05058c8e451ca57f/examples/custom-server-express/server.js#L21-L23

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

服务器.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 and

即将/en/index将渲染index lang: en因此

希望这可以帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐