简体   繁体   English

我可以在 getStaticProps 中使用 UseEffect 挂钩吗?

[英]Can I use the UseEffect hook inside getStaticProps?

I have a doubt.. can I use a useEffect inside getStaticProps?我有疑问..我可以在 getStaticProps 中使用 useEffect 吗?

I'm trying to run a function inside getStaticProps... it works.. but I don't know if it is the recommended thing to do.我正在尝试在 getStaticProps 中运行 function ......它可以工作......但我不知道这是否是推荐的做法。

  useEffect(() => {
    remarkBody()
  }, [body, blogPostCollection])

If not... what is the best way to run it?如果不是...运行它的最佳方法是什么?

useEffect is used to execute code when component is mounted on client side, and when specific variables change. useEffect用于在客户端挂载组件时以及特定变量发生变化时执行代码。

getStaticProps is run only once on server side and at build time. getStaticProps仅在服务器端和构建时运行一次。 You can put your code in the body of the function directly.您可以将代码直接放在 function 的主体中。

And anyway if you do it you will have this error:无论如何,如果您这样做,您将遇到此错误:

Error: Invalid hook call.错误:无效的挂钩调用。 Hooks can only be called inside of the body of a function component.钩子只能在 function 组件的主体内部调用。

in next.js data is fetched on the server.在 next.js 中,数据是在服务器上获取的。 This is the key aspect of server side rendering.这是服务器端渲染的关键方面。 The main purpose of server-side rendering, is sending populated page, so browser crawlers can analyze the response page and this help better seo for your page.服务器端渲染的主要目的是发送填充页面,以便浏览器爬虫可以分析响应页面,这有助于更好地为您的页面进行 seo。 When client makes a request, before sending the response, next.js runs getStaticProps or getServerSideProps.当客户端发出请求时,在发送响应之前,next.js 会运行 getStaticProps 或 getServerSideProps。

However useEffect runs on the client-side.但是useEffect在客户端运行。 The purpose of useEffect , to get data before components mount, so you can use that data inside the component. useEffect的目的是在组件挂载之前获取数据,以便您可以在组件内部使用该数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM