【问题标题】:Why component is called twice in Next.js?为什么组件在 Next.js 中被调用两次?
【发布时间】:2020-05-08 15:20:03
【问题描述】:

这是我的pages/index.js 项目中的next.js

const Index = () => {
  console.log('Index Component Called');
  return (
    <div>Hello</div>
  )
}

export default Index;

控制台日志函数在CLIENT端调用两次,在next.js节点SERVER

调用一次

【问题讨论】:

    标签: next.js


    【解决方案1】:

    我猜是因为next.js 中的Pages 是服务器端渲染(或预渲染)的。
    因此,在这种情况下,当 next.js 呈现您的页面(服务器端)时,脚本将 console.log("Index Component Called") 然后在您的前端反应它是 hydrating 所以来自服务器的所有代码都应该再次执行。
    在 next.js 中,您可以在 getInitialProps 中执行服务器端代码,并且只能在页面中而不是组件中。

    【讨论】:

      猜你喜欢
      • 2017-01-22
      • 1970-01-01
      • 2021-07-13
      • 2021-11-25
      • 2015-12-24
      • 2012-12-10
      • 2014-01-11
      • 1970-01-01
      相关资源
      最近更新 更多