1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

getInitialPropsを使ってないのにTypeError: Cannot read properties of undefined (reading 'getInitialProps')エラー

Last updated at Posted at 2024-03-03

エラーを発生した時のソースコードは?

Next.jsの学習中に発生したエラー。

TypeError: Cannot read properties of undefined (reading 'getInitialProps')

getInitialPropsは非推奨で使用していないはずなのに... :thinking:うーん

コードを見て間違いを探した結果

pages/_app.tsx
//自分の間違い。exportの後のdefaultが抜けている。
import type { AppProps } from 'next/app'
export function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}
pages/_app.tsx
//正解
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

引用:Routing: Custom App | Next.js

学び1:writing_hand:名前付きエクスポートとデフォルトエクスポートの違い

export function MyApp:point_left:名前付きエクスポート

インポート時に { } 内に指定した名前でインポートする必要がある。

import { MyApp } from './MyApp';

export default function MyApp:point_left:デフォルトエクスポート

任意の名前でインポートする必要がある。

1つのモジュール内に1つだけexport defaultできる。

import MyApp from './MyApp';
//もしくは、
import App from './MyApp';//インポート時に任意の名前なので、exportしている時の関数名と違ってもOK

学び2:writing_hand:_app.jsはどんなファイル?

  • Next.jsは、_app.jsファイルを最初に読み込み、その中で定義されたAppコンポーネントを使用して、各ページのレンダリングを処理する。

  • _app.jsファイルは、すべてのページに共通のレイアウトやグローバルな振る舞いを定義するためのファイル。したがって、Appコンポーネントは_app.jsファイル内でエクスポートされる必要がある。

  • pages/_app.jsファイル内でAppコンポーネントがデフォルトエクスポートされている場合、Next.jsはそのファイルを自動的に読み込み、Appコンポーネントを使用してページのレンダリングを行う。そのため、明示的にimport文を使用してAppコンポーネントをインポートする必要はない。

学び3:writing_hand:TypeError: Cannot read properties of undefined (reading 'getInitialProps')とは

このエラーは、通常、ページコンポーネント内でgetInitialPropsが定義されているかどうかをNext.jsが検出しようとするときに発生する。

:warning:Next.jsが最初に読み込む_app.jsファイルを正しく読み込めていない。
↓getInitialPropsが存在しない場合、(自身のソースにもgetInitialPropsは存在しなかった)

:warning:getInitialPropsが存在しないので、Next.jsは代わりに何も返さないコンポーネントを返そうする。

:warning:その結果、undefinedが返される。

:warning:その後、ページコンポーネントでこのundefinedにアクセスしようとすると、TypeErrorが発生。

デフォルトエクスポートを使用することで、Next.jsが_app.jsファイルを正しく読み込み、Appコンポーネントを適切に処理することができる。

非推奨のgetInitialPropsとは?
ページ内のサーバーサイドレンダリングを可能にし、初期データを追加出来るようになります。つまり、既にデータが追加されているページをサーバーから送信するということです。これは特に SEO 対策に有効です。
引用:Data Fetching: getInitialProps | Next.js

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?