繁体   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