将变量从自定义服务器传递到NextJS中的组件 [英] Pass variables from custom server to components in NextJS
问题描述
我已经在NextJS中设置了自定义服务器,如图所示此处用于自定义路由.
I have set up a custom server in NextJS as illustrated here for custom routing.
server.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}`)
})
})
对于i18n,它基本上将/en/url
映射到/another_url
.
it basically maps /en/url
to /another_url
for i18n.
我知道我可以在这里使用query
参数并在组件中读取它,但是我想将选项传递给App
而不重新检查URL.是否可以在不读取URL的情况下将选项从服务器级别传递到应用程序级别?
I understand I can use query
parameter here and read it in the component, but I would like to pass options to the App
without rechecking the URL. Is it possible to pass options from server level to app level without reading the URL?
经过一番调查,对标记出的答案进行了解释,解释说query
实际上并不意味着URL中的查询参数,而是将值从服务器传递给客户端.带有误导性的词,因为它仅表示客户端操作.这正是我所需要的.
After a bit of investigating the marked answer explained that query
actually does not mean query-paramter in the URL, rather than passing a value from the server to client. Misleading word as it indicates only client side action. This was exactly what I needed.
推荐答案
以下是从服务器到客户端
Here is an example of custom-server-express where they pass id
from server to client side
所以您的情况将是这样
server.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}`);
});
});
pages/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
希望这会有所帮助!
这篇关于将变量从自定义服务器传递到NextJS中的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!