[英]How do I log some string on server and give it back to component as props using Next.js?
I apologize for a silly question, but I'm a newbie in Next.js, and I was given a task to "Add "Hello from SSR"
string to a server log and give it back to MyWonderfulComponent
", any ideas on how to do this?我为一个愚蠢的问题道歉,但我是 Next.js 的新手,我的任务是“将
"Hello from SSR"
字符串添加到服务器日志并将其返回给MyWonderfulComponent
”,关于如何执行此操作的任何想法?
This is the code example这是代码示例
export default function Page(props) {
return <MyWonderfulComponent props={props}>I'm text from a component</MyWonderfulComponent>
}
function MyWonderfulComponent({ id, options, children, other }) {
const [summ, setSumm] = useState(other);
useEffect(() => {
if (id && options) {
setSumm(summ + 1);
}
}, [id, options]);
console.log(summ);
return (
<React.Fragment>
<h1>Hello World!</h1>
<Grid>
<Grid xs={12}>{children}</Grid>
</Grid>
</React.Fragment>
);
}
I suggest creating the "Hello from SSR" string in getStaticProps , one of the functions you can set on your components which will be called on the server-side.我建议在getStaticProps中创建“Hello from SSR”字符串,这是您可以在组件上设置的函数之一,它将在服务器端调用。
From the Next.js docs on data-fetching :来自Next.js 关于数据获取的文档:
We'll talk about the three unique Next.js functions you can use to fetch data for pre-rendering:
我们将讨论可用于获取数据以进行预渲染的三个独特的 Next.js 函数:
- getStaticProps (Static Generation): Fetch data at build time.
getStaticProps (静态生成):在构建时获取数据。
- getStaticPaths (Static Generation): Specify dynamic routes to pre-render based on data.
getStaticPaths (静态生成):指定动态路由以根据数据进行预渲染。
- getServerSideProps (Server-side Rendering): Fetch data on each request.
getServerSideProps (服务器端渲染):获取每个请求的数据。 In addition, we'll talk briefly about how to fetch data on the client side.
此外,我们将简要讨论如何在客户端获取数据。
Untested, but did you try something like this?未经测试,但你尝试过这样的事情吗?
export async function getStaticProps (context) {
const str = 'Hello from SSR'
console.log(str) // log on the server-side
return {
props: { str } // will be passed to the page component as props
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.