'ОШИБКА TypeError: Невозможно прочитать свойство' concat 'из неопределенного' - PullRequest
0 голосов
/ 11 марта 2020
import {LOADING_POSTS, GET_ERROR, UPDATE_POSTS} from './postTypes';

const initialState = {
    loading : false,
    posts : [],
    error : ''
};

const postReducer = (state = initialState, action) => {
    switch(action.type){
        case LOADING_POSTS :
            return {
                ...state,
                loading : true
            };
        case UPDATE_POSTS : 
            return {
                loading : false,
                posts : state.posts.concat(action.data),
                error : ''
            };
        case GET_ERROR : 
            return {
                ...state,
                loading : false,
                error : action.error
            };
        default : return state;
    }
}

export default postReducer;

Всякий раз, когда я пытаюсь обновить сообщения, я получаю сообщение «ERROR TypeError: Невозможно прочитать свойство concat of undefined». Есть идеи, в чем может быть проблема?

Ответы [ 2 ]

0 голосов
/ 11 марта 2020

Я попробовал это, и это действительно сработало!

import {LOADING_POSTS, GET_ERROR, UPDATE_POSTS} from './postTypes';

const initialState = {
    loading : false,
    posts : [],
    error : ''
};

const postReducer = (state = initialState, action) => {
    switch(action.type){
        case LOADING_POSTS :
            return {
                ...state,
                loading : true
            };
        case UPDATE_POSTS : 
            return {
                loading: false,
                posts: state.posts ? state.posts.concat(action.data) : action.data,
                error : ''
            };
        case GET_ERROR : 
            return {
                ...state,
                loading : false,
                error : action.error
            };
        default : return state;
    }
}

export default postReducer;
0 голосов
/ 11 марта 2020

Похоже, что state.posts не установлено во время попытки concat новых данных для него.

Вы можете добавить туда чек, чтобы предотвратить ошибки (если он вызывается только до установки posts). Если posts вообще не установлен, выясните, почему он не проходит.

return {
  loading : false,
  posts : (state.posts 
    && Array.isArray(state.posts) // Extra check, you do not need this one if you are certain of the type
    && state.posts.concat(action.data)),
  error : ''
};

Надеюсь, это поможет

...