【问题标题】:Launch-time initialization in Next.js static/exported siteNext.js 静态/导出站点中的启动时初始化
【发布时间】:2019-03-26 02:13:13
【问题描述】:

我正在尝试使用 Next 为 Electron 应用程序供电。 electron-next 使用 Next 的静态站点模式进行生产构建,它在构建时调用 getInitialProps,而不是在启动时。

start.js(初始渲染页面)

import Link from 'next/link'

export default function Start({date}) {
  return (
    <div>
      <div>Date is {date}</div> {/* <- will always be the build time */}
      <Link href="/about">
        <a>Take me to the About page</a>
      </Link>
    </div>
  )
}

Start.getInitialProps = () => {
  return {
    date: "" + new Date()
  }
}

有趣的是,使用Link 导航到别处实际上会导致动态的getInitialProps 调用。

about.js

import Link from 'next/link'

export default function About({date}) {
  return (
    <div>
      <div>Date is {date}</div> {/* <- will be the time the link was clicked */}
      <div>Important info about this app</div>
    </div>
  )
}

About.getInitialProps = () => {
  return {
    date: "" + new Date()
  }
}

有没有一种简单的方法来获取初始路由的动态行为?我想这在静态网站中也会有很多用例。

【问题讨论】:

    标签: next.js static-site


    【解决方案1】:

    我最终没有使用getInitialProps。相反,我使用的是 React 钩子。它的工作原理基本上是这样的:

    async function useModel() {
      const modelRef = useRef(null)
    
    
      // This hook will render at build-time by Next.js's static site, in which
      // case the conditional loading of the model will never happen.
      //
      // At startup-time, it will be re-renderered on the Electron renderer thread,
      // at which time, we'll actually want to load data.
      if (process.browser && !modelRef.current) {
        const m = new Model()
        await m.init() // <- Assumed to have some async fetching logic
        modelRef.current = m
      }
    
      return modelRef.current
    }
    

    然后,顶层组件可以轻松地使用模型的存在来确定下一步要做什么:

    function Start() {
      const model = useModel()
    
      if (!model) {
        return <div>Loading...</div>
      } else {
        return <MyProperUI model={model} />
      }
    }
    

    或者,您可以轻松地对其进行装配以显示未填充的默认 UI 或其他任何内容。

    所以基本上,对于您想要只运行一次、服务器端/构建时间或客户端的代码,请使用getInitialProps。否则,使用其他初始化方式。如此处所示,钩子以非常少的样板文件实现了这一点。

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 2021-06-22
      • 2022-10-22
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多