【问题标题】:'ERROR TypeError: Cannot read property 'concat' of undefined''错误类型错误:无法读取未定义的属性'concat''
【发布时间】:2020-03-11 18:14:16
【问题描述】:
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'”。任何想法可能是什么问题?

【问题讨论】:

  • 是的,我做了,什么也没出来...
  • 在调用postReducer函数时检查一下,如果你想使用初始状态(因为你有默认值),你应该调用它:postReducer(undefined, action),或者最好把你的可选参数在函数结束时。
  • 你可以试试:从参数列表中删除= initialState,并将其放在你的开关之前的函数顶部 -> if (typeof state === 'undefined') {return initialState}
  • @MiroslavGlamuzina 我尝试了你的建议,但我收到一条错误消息,提示未定义 initialState,这解释了为什么 state.posts 也未定义

标签: javascript arrays redux react-redux


【解决方案1】:

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

希望对你有帮助

【讨论】:

  • 如果在initialState 中他已经设置为posts : [],为什么会是undefined
  • @pmiranda 几个不同的可能原因:1)OP 可能会修改帖子范围之外的数据。 2) OP 目前可能没有使用 ES6,我不认为default arguments 工作非 ES6(基于文档>redux.js.org/basics/reducers)。我只知道posts 在那个时候不存在。
  • 我试过了,但条件总是假的,返回未定义
  • @houssamghannoum 在reducer 中state 的值是多少?
【解决方案2】:

我试过了,它确实有效!

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-30
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2021-11-22
    • 2018-07-12
    相关资源
    最近更新 更多