簡體   English   中英

為什么我不能在 React/Redux 中索引我的對象? 類型錯誤:無法讀取未定義的屬性“1”

[英]Why Can't I index my object in React/Redux? TypeError: Cannot read property '1' of undefined

我目前正在做一個個人項目,我正在嘗試創建一個膳食計划表。 我目前正在使用 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>
     );
   });
 };```

我認為您已經創建了數組對象。 您可以創建對象數組來代替它。 通過這種方式,您可以分別迭代每個項目。

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

現在您映射這個數組,您將分別獲得每個項目。 快樂編碼!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM