簡體   English   中英

嘗試訪問 React state 變量中的嵌套數組時如何解決未定義錯誤?

[英]How to solve undefined error when trying to access a nested array in a React state variable?

我正在嘗試構建一個表單,您可以在其中動態添加字段和子字段。 例如,我的表單如下所示:

    Store information:
      Name
      Items inventory: [] (this is the nested array part,
            you press a button and can add another item to the inventory)
            ***Buttons to add more items to this store***

      ***Buttons to add more stores***
    

我用來實現此目的的代碼如下所示。 我已經更新以反映我到目前為止得到的答案以及正確的語法(結束標簽有問題)

function StoreForm() {
  const [storeInputs, setStoreInputs] = useState([
    { storeName: "", items: [{ itemName: "" }] },
  ]);
   ///...
    
    return (
        {storeInputs.map((store,index) => 
        {
            //input data here
            
            {store.items.map((item,i) => 
                    {
                    //This is where it throws the undefined error
                    //do something
                    }
                )
            }
         }
        )
    )
   
}

上面的代碼現在可以在第一次運行時運行,但是當我嘗試向表單添加另一個商店時,它再次拋出未定義的錯誤。 這是我用於添加另一家商店的按鈕的代碼:

  const handleRemoveStore = (index) => {
    const list = [...storeInputs];
    list.splice(index, 1);
    setItemsInputs(list);
  };

  const handleAddStore = () => {
    setItemsInputs([...storeInputs, { storeName: "", items: [{ itemName: "" }] }]);
  };

感謝您到目前為止的回答!

return (
        {storeInputs.map(store,index) => 
        {
            //input data here
            
            {storeInputs.items.map(item,i) => 
                {
                    //This is where it throws the undefined error
                    //do something
                }
            }
        }
    )

你 map 在 storeInputs 上兩次,你需要做一些事情,比如:

return (
        {storeInputs.map((input,index) => 
    {
        //input data here
        
        {input.items.map((item,i) => 
            {
                //This is where it throws the undefined error
                //do something
            }
        }
    }
)

小心參數周圍的 () ,你這樣做:

x.map(a, index) => {})

事實上是:

x.map((a, index) => {})

第一個(用於 map 方法,第二個用於 map 中的 function 的參數。

storeInputs state 在內部映射中沒有任何items屬性到 map。 該屬性屬於從外循環映射的store object。

function StoreForm() {
  const [storeInputs, setStoreInputs] = useState([
    { storeName: "", items: [{ itemName: "" }] },
  ]);
  
  ...
    
  return storeInputs.map((storeInput, index) => {
    // input data here
  
    return (
      ...          
      {storeInput.items.map((item, i) => { ... })}
      ...
    );
  });
}

暫無
暫無

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

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