gpt4 book ai didi

node.js - Next JS 自定义服务器 app.render 不将查询传递给组件

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:57 24 4
gpt4 key购买 nike

我尝试使用 app.render 传递 userData,但在服务器端渲染 router.query 时> 是空的,尽管我已经传递了userData!是 NextJS 的 bug 还是我做错了什么?

app.js:

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

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 === '/index') {
app.render(req, res, '/index', {
userData: {
id: 1,
name: 'admin'
}
})
} else {
handle(req, res, parsedUrl)
}
}).listen(3333, err => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})

pages/index.js:

import { useRouter } from 'next/router'

export default () => {
const router = useRouter();
const { query } = router;

return (
<div>
Query: {JSON.stringify(query)}
</div>
);
};

最佳答案

If getInitialProps is absent, Next.js will statically optimize your page automatically by prerendering it to static HTML. During prerendering, the router's query object will be empty since we do not have query information to provide during this phase. Any query values will be populated client side after hydration.

您可以使用getInitialProps访问您的查询。
使用useRouter:

import { useRouter } from 'next/router'
const Index = () => {
const router = useRouter();
const { query } = router;

return (
<div>
Query: {JSON.stringify(query)}
</div>
);
};

Index.getInitialProps = async () => {
return {};
};
export default Index

带有类组件:

import React from 'react'

class Index extends React.Component {
static async getInitialProps (context) {
let query = context.query;
return {query}
}

render() {
let {query} = this.props
return (
<div>
Query: {JSON.stringify(query)}
</div>
);
}
}
export default Index

或者如果您更喜欢功能组件:

const Index = (props) => (
<div>
Query: {JSON.stringify(props.query)}
</div>
)

Index.getInitialProps = async ( context ) => {
let query = context.query;
return {query}
}

export default Index

请注意,显然这适用于 /index,但不适用于 /

关于node.js - Next JS 自定义服务器 app.render 不将查询传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57973867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com