getInitialProps

Bilmenizde fayda var: getInitialProps eski bir API'dir. Kullanmanızı öneririz getStaticProps veya getServerSideProps onun yerine.

getInitialProps sayfa için varsayılan dışa aktarılan React bileşenine eklenebilen bir async işlevidir. Sayfa geçişleri sırasında hem sunucu tarafında hem de istemci tarafında tekrar çalışacaktır. Fonksiyonun sonucu React bileşenine props olarak iletilecektir.

pages/index.tsx
import { NextPageContext } from 'next'
 
Page.getInitialProps = async (ctx: NextPageContext) => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const json = await res.json()
  return { stars: json.stargazers_count }
}
 
export default function Page({ stars }: { stars: number }) {
  return stars
}

Bildiğim iyi oldu:

  • getInitialProps adresinden döndürülen veriler sunucu tarafından işlenirken serileştirilir. getInitialProps adresinden döndürülen nesnenin düz bir Object olduğundan ve Date, Map veya Set kullanmadığından emin olun.
  • İlk sayfa yüklemesi için getInitialProps yalnızca sunucu üzerinde çalışacaktır. getInitialProps daha sonra istemci üzerinde de çalışacaktır. next/link bileşenini kullanarak veya next/router.
  • getInitialProps özel bir _app.js içinde kullanılıyorsa ve gidilen sayfa getServerSideProps kullanıyorsa, getInitialProps da sunucu üzerinde çalışacaktır.

Context Object

getInitialProps aşağıdaki özelliklere sahip bir nesne olan context adlı tek bir argüman alır:

NameDescription
pathnameCurrent route, the path of the page in /pages
queryQuery string of the URL, parsed as an object
asPathString of the actual path (including the query) shown in the browser
reqHTTP request object (server only)
resHTTP response object (server only)
errError object if any error is encountered during the rendering

Caveats