首页 > 解决方案 > 为什么我尝试映射 redux 数组时会出现错误?

问题描述

我正在使用 React Hooks + Redux。
我有一个包含数组的对象:

{
  id: "c59a3203-af94-49c3-abb6-87073619fbce"
  type: "block"
  attributes: {
    title: "THis is the first title"
    status: "published"
    published: true
    attachments: (4) [{…}, {…}, {…}, {…}] <== this is array I need to access 
    articles: [{…}]
    external_resources: []
  }
}

单击时,我将附件数组(见下文)加载到 Redux 中,并使用 hook 将其提取到我的组件中useSelector

(4) [{…}, {…}, {…}, {…}]
0: {id: "f15dbb5b-79e5-4204-9161-77bd6917814b", type: "attachment", attributes: {…}}
1: {id: "4971d5c8-df8e-4930-bafe-a12160493371", type: "attachment", attributes: {…}}
2: {id: "a275d3da-ad26-4144-819c-8f2db972ad6e", type: "attachment", attributes: {…}}
3: {id: "c15ea08c-a12f-4822-84bf-580f27fa1c94", type: "attachment", attributes: {…}}

如您所见,这是一个数组,但无论出于何种原因,当我通过使用useSelector并映射它从我的组件中调用它时,我收到以下错误消息:

TypeError: Cannot read property 'map' of undefined

这里的组件:

const attachmentsData = useSelector(
  state => state.attachments.attachmentsData,
  shallowEqual
);

console.log(attachmentsData.map(x => x)) <== ERROR
console.log(attachmentsData) <=== SHOWS THE ARRAY WITHOUT ERRORS

这是减速机:

const initialState = {
    attachmentsRaw: [],
    attachmentsData: []
};

const attachmentsReducer = (state = initialState, action) => {
    switch (action.type) {
        case ATTACHMENTS.GET_START:
            return {
                ...state,
                attachmentsRaw: getLoadingState()
            };

        case ATTACHMENTS.GET_SUCCESS:
            return {
                ...state,
                attachmentsRaw: getReadyState(action.data),
                attachmentsData: action.data
            };

        case ATTACHMENTS.GET_FAIL:
            return {
                ...state,
                attachmentsRaw: getErrorState()
            };

        default:
            return state;
    }
};
export default attachmentsReducer;

我究竟做错了什么?
我可以说,当组件加载时,Redux 需要几分之一秒来加载数据,这意味着在我的组件第一次渲染中,常量attachmentsData是一个空数组 []。

任何帮助表示赞赏。乔

标签: reactjsreduxarray.prototype.map

解决方案


我认为您在填充数组之前获取数据

用这个

附件数据?附件Data.map(x => x):无效0


推荐阅读