noah.plus

エラー「Reducer returned undefined during initialization」(React/Redux)

2018-10-07

React/Reduxを使って開発をしたときに以下のようなエラがー発生した。

Reducer “searchState” 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.

このエラーは、reducer が初期化時に undefined を返しているために発生しているとのこと。その時の reducer のコードがこちら。

import {SEARCH_REQUESTED, SEARCH_SUCCEEDED, SEARCH_FAILED, SEARCH_CLEAR} from './types'

const initialState = {
    isFetching: false,
    responses: []
};

function searchReducer (state = initialState, action) {
    const {type, payload} = action;
    switch (type) {
        case SEARCH_REQUESTED:
            return {
                ...state,
                isFetching: true
            };
        case SEARCH_SUCCEEDED:
            return {
                ...state,
                isFetching: false,
                responses: payload.items
            };
        case SEARCH_FAILED:
            return {
                ...state,
                isFetching: false
            };
        case SEARCH_CLEAR:
            return {
                ...state,
                responses: []
            };
    }
}

export default searchReducer;

原因

switch文で default の条件を設定し忘れている。

解決方法

default の条件として、state をそのまま返すようにする。

修正したコードは以下。

import {SEARCH_REQUESTED, SEARCH_SUCCEEDED, SEARCH_FAILED, SEARCH_CLEAR} from './types'

const initialState = {
    isFetching: false,
    responses: []
};

function searchReducer (state = initialState, action) {
    const {type, payload} = action;
    switch (type) {
        case SEARCH_REQUESTED:
            return {
                ...state,
                isFetching: true
            };
        case SEARCH_SUCCEEDED:
            return {
                ...state,
                isFetching: false,
                responses: payload.items
            };
        case SEARCH_FAILED:
            return {
                ...state,
                isFetching: false
            };
        case SEARCH_CLEAR:
            return {
                ...state,
                responses: []
            };
        // 初期条件を忘れずに書く
        default:
            return state;
    }
}

export default searchReducer;

すごく凡ミスだった。気をつけたい。


noah.plus