首页 > 解决方案 > '错误类型错误:无法读取未定义的属性'concat''

问题描述

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;

每当我尝试更新帖子时,我都会收到“错误类型错误:无法读取未定义的属性 'concat'”。任何想法可能是什么问题?

标签: javascriptarraysreduxreact-redux

解决方案


似乎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 : ''
};

希望这可以帮助


推荐阅读