尝试访问 React 状态变量中的嵌套数组时如何解决未定义错误?

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
                }
            }
        }
    )

您在 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) => {})

第一个 ( 用于映射方法,第二个用于映射中函数的参数。

storeInputs 状态在内部映射中没有任何 items 属性 映射。 属性 属于从外循环映射的 store 对象。

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