【问题标题】:Why Can't I index my object in React/Redux? TypeError: Cannot read property '1' of undefined为什么我不能在 React/Redux 中索引我的对象? TypeError:无法读取未定义的属性“1”
【发布时间】:2019-12-01 10:12:00
【问题描述】:

我目前正在从事一个个人项目,我正在尝试创建一个膳食计划表。我目前正在使用 React/Redux 分别构建我的应用程序和管理我的状态。 我觉得我几乎完成了,除了我现在正在采取的这个非常奇怪的违反直觉的步骤。我目前正在尝试迭代一个全局 redux tableState 对象,该对象包含我的表的状态。现在,由于我的表和表状态被定义为具有模式的对象(见下文),我不明白为什么我不能通过tableState[mealtime][index] 索引每个项目。我不断收到TypeError: Cannot read property '0' of undefined 的错误。我将其理解为我的对象为空,但为什么呢?此外,如果我执行tableState['breakfast'][1],我实际上会在控制台中看到我期望收到的值('Select')。这里发生了什么?为什么在控制台中我能够按预期索引数组时浏览器会抛出此错误?

编辑:所以我刚刚意识到我忘了添加一个非常重要的细节(我刚刚发现了这一点),我从一个 API 获得这个状态,我正试图通过useEffect API 更新它。如果我从状态对象中删除这个调用,一切都会按预期工作。但是,当我在 renderRows 方法上方运行这段代码时,我得到了错误。我在这里假设我遇到了问题,因为这是一个异步调用,并且状态正在更新中,这就是它未定义的原因。

/// Defined in seperate file
const tableInitState: ITableInitState = {
 tableState: {
   breakfast: [
     'Select',
     'Select',
     'Select',
     'Select',
     'Select',
     'Select',
     'Select'
   ],
   lunch: [
     'Select',
     'Select',
     'Select',
     'Select',
     'Select',
     'Select',
     'Select'
   ],
   dinner: [
     'Select',
     'Select',
     'Select',
     'Select',
     'Select',
     'Select',
     'Select'
   ]
 }
};

/// Defined in seperate file
// Where onMount is a dispatch function to retreive a state from the API and set in the the store.
useEffect(() => {
   onMount();
 }, []);

const renderRows = () => {
   console.log(tableState['breakfast'][1]);
   return mealTimes.map((mealTime: string, _) => {
     return (
       <TableRow key={mealTime}>
         <TableCell>{mealTime}</TableCell>
         {daysofWeek.map((value: string, index: number) => {
           console.log(`mealTime is: ${mealTime}, the index is ${index}`);
           const currentMeal = tableState['breakfast'][1];
           return (
             <TableCell size="small" key={value}>
               <MealOptionsList
                 mealtime={mealTime}
                 tableIndex={index}
                 currentMeal={currentMeal}
               />
             </TableCell>
           );
         })}
       </TableRow>
     );
   });
 };```

【问题讨论】:

  • 你能显示它运行时得到的控制台输出吗?
  • 应该是tableState.breakfast[1]
  • 刚刚添加了一个编辑,我发现了问题。它与我在尝试加载初始化状态时进行的异步调用有关。
  • @AlwaysLearning console.log(tableState['breakfast'][1]); 输出 Select

标签: javascript reactjs typescript redux react-redux


【解决方案1】:

我认为您已经创建了数组对象。 取而代之的是,您可以创建对象数组。通过这种方式,您可以分别迭代每个项目。

const arr = [
      breakfast = {
          'Select',
          'Select',
      },
      lunch = {
          'Select',
          'Select',
      },
      dinner = {
          'Select',
          'Select',
      }
]

现在您映射此数组,您将分别获取每个项目。 编码愉快!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2021-05-18
    • 2021-03-01
    • 2019-03-19
    • 2019-10-29
    • 1970-01-01
    相关资源
    最近更新 更多