Next.js静态/导出站点中的启动时初始化

时间:2019-03-26 02:13:14

标签: next.js static-site

我正在尝试使用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()
  }
}

是否有一种轻松的方法来获取初始路线的动态行为?我想这在静态站点中也会有很多用例。

1 个答案:

答案 0 :(得分:0)

我最终根本不使用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。否则,请使用其他初始化方法。如此处所示,钩子允许使用最少的样板来实现此目的。