reactjs - 为什么我尝试映射 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
是一个空数组 []。
任何帮助表示赞赏。乔
解决方案
我认为您在填充数组之前获取数据
用这个
附件数据?附件Data.map(x => x):无效0
推荐阅读
- ruby - Ruby 中一个匿名函数的参数
- android - 签名的 apk 不适用于 7.1 以下的设备。*
- azure - 获取启用 MSI 的应用服务的 AAD 应用程序 ID 的最简单方法是什么
- javascript - Angular 6中的数据不通过路由
- c# - SSIS 包 - 以编程方式配置格式版本
- android - 如何在活动中制作应用内按钮键盘?
- xml - 如何更改其中一个属性的值?
- node.js - nodejs中swagger-jsdoc设置的语法错误
- python - python ProcessPoolExecutor在函数中不起作用
- c# - 两个日期之间的计数(C#,CultureInfo)