"错误类型错误: 无法读取未定义的属性'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;

每当我尝试更新帖子时,我都会得到"ERROR TypeError:Cannot read property"concat"of undefined"。知道可能是什么问题吗?

尝试向concat发送新数据时,似乎未设置state.posts

您可以在其中抛出一个检查以防止出现错误(如果这只是在设置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 : ''
};

希望这能帮助

我试过了,它确实有效!

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;

相关内容

最新更新