概要
React アプリを開発する上で発生したエラーの原因と対策を忘れないためのメモです。
状況
某商品紹介用の Web アプリの商品追加画面制作中に発生。
エラー
> Error: Reducer "products" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.
コード
export const ProductsReducer = (state = initialState.products, action) => {
switch (action.type) {
}
};
原因
reducer の switch 文の中に default のケースを設定していなかったこと
対策
switch 文に default のケースを追加することで解決
export const ProductsReducer = (state = initialState.products, action) => {
switch (action.type) {
default:
return state;
}
};