首页 > 解决方案 > 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;

标签: javascriptreactjsredux

解决方案


像下面这样更改减速器逻辑,然后它将起作用

switch(action.type) { default: return ["hats", "sneakers"].map(key =>INITIAL_STATE['collections'][key]) }

谢谢


推荐阅读