我使用的是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中,并使用钩子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
是一个空数组[]。
感谢您的帮助。Joe
attachmentsData
可能仍然未定义或在您尝试映射到它以修复它时未填充,将其添加到代码attachmentsData && attachmentsData.length && attachmentsData.map...
中
如何将数据加载到Redux?如果在加载时有可用的静态数据,则应将其放入reducer的initialState
中,而不是随后注入。
https://redux.js.org/recipes/structuring-reducers/initializing-state/
您可以先检查附件数据的存在性,然后再映射数组。
我认为你在填充数组之前就已经得到了数据
使用这个
附件数据?附件Data.map(x=>x(:无效0
根据Shmili和Study Mania的建议,我发现了一种更清洁的解决方案:
(attachmentsData || []).map(item => ( ....
这很奇怪。在控制台日志中,我可以看到attachmentsData
被渲染了3次。第一次是在redux中配置的空数组,第二次是未定义的(这就是问题所在(,第三次是填充数组。
所以,我必须调查为什么,首先,它渲染了3次,其次,为什么第二次是未定义的。
当我修复未定义的时,我会在这里发布。