javascript - React Shows 中的 Reducer:无法将 undefined 或 null 转换为对象
问题描述
我需要将 reducer 中的一些数据从数组转换为对象。所以我曾经Object.keys
这样做过。但是我开始收到无法转换未定义的错误。
经过相当多的故障排除后,我已将减速器中的代码简化为最简单的形式,如下所示,但我仍然看到相同的错误。有人可以告诉这里有什么问题吗?当然,既然我已经删除了Object.keys
,我看到的错误略有不同,但主要问题似乎是相同的。状态中的对象未定义。
谢谢!
只是在我 console.log(state.collections["hats"]);
在 switch 语句之前添加一些内容时,它会按预期显示数据,即“帽子”键的对象/值
TypeError: Cannot read property 'hats' of undefined
我简化的 Reducer 代码:
import SHOP_DATA from '../../data/shop.data.js';
const INITIAL_STATE = {
collections: {
hats:{
id: 1,
title: 'Hats',
routeName: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
price: 25
},
{
id: 2,
name: 'Blue Beanie',
price: 18
}
]
},
sneakers: {
id: 2,
title: 'Sneakers',
routeName: 'sneakers',
items: [
{
id: 10,
name: 'Adidas NMD',
price: 220
},
{
id: 11,
name: 'Adidas Yeezy',
price: 280
}
]
}
}
}
const collectionsReducer = (state= INITIAL_STATE, action) => {
switch(action.type) {
default:
return ["hats", "sneakers"].map(key => state.collections[key]);
}
}
export default collectionsReducer;
解决方案
像下面这样更改减速器逻辑,然后它将起作用
switch(action.type) { default: return ["hats", "sneakers"].map(key =>INITIAL_STATE['collections'][key]) }
谢谢
推荐阅读
- c# - 条码 ASP.NET C# 问题
- html - 在 PhpStorm 中选择标签。我想在 PhpStorm 中打开标签,关闭它并将选择器放在中间(就像在 Sublime 中一样)
- php - 是否可以在 MySQL 中的其他记录之间添加记录?
- redis - redis.call 失败
- algorithm - 算法:得到一个 O(n lg n/ lg k) 算法而不是 O(n lg n/k)
- image-processing - 如果我用笔记本电脑编码视频,会有任何痕迹吗?
- jquery - 使用 jQuery woocommerce 选择变体选项
- php - 如何使用数组上传多个图像?
- scala - 使用来自另一个函数的请求调用 scala 函数
- c++11 - 如何从 Boost mutable_buffers_1 中获取数据?