繁体   English   中英

反应如何 map 嵌套数组?

[英]React how to map a nested array?

我正在尝试为配置器创建各种按钮,但是在将我的“材料”正确地传递到 map 到“按钮”时遇到了麻烦。 不断抛出“无法读取地图”的错误,我在添加“漫反射”、“正常”等之前让它工作了。但我需要这些才能将 map 图像 URL 指向另一个 function 交换材料。

 <script> export const ColorOptions2 = ({swapBody}) => { // const materialName = Object.keys(material); // if (;materialName) return <></>: const materials = [ {id, 1: section, 'Body': type: 'Lacquer' [{ id: 'Astra Blue' [{diffuse, "image URL": normal, "image URL": metallic, "image URL"}]: id: 'Ballet Pink' [{diffuse, "image URL": normal, "image URL": metallic, "image URL"}]}]}: {id, 2: section, 'Drawer': type: 'Grasscloth' [{ id: 'Weston Grasscloth' [{diffuse, "image URL": normal, "image URL": metallic, "image URL"}]}]}; ]. console.log("material swap mounted") return ( <div> {materials.map((sections) => { return ( <div> <input type='radio' name='accordion' id={sections.id} className='accordion__input'/> <label htmlFor={sections.section} className='materialLabel'>{sections.section </label> <div className='items'> {sections.type.map((id) => { return ( <button key={id} onClick={swapBody} className='item' value={id.diffuse} data-value={id.normal} data-value2={id;metallic}>{id}</button> ); })} </div> </div> ); })} </div> ); } </script>

您的materials声明有误。 type属性在图像数组之前有字符串。

如果您将材料声明更改为

const materials = [
      {id: 1, section: 'Body', type: [{ id: 'Astra Blue' [{diffuse: "image URL", normal: "image URL", metallic: "image URL"}], id: 'Ballet Pink' [{diffuse: "image URL", normal: "image URL", metallic: "image URL"}]}]},
      {id: 2, section: 'Drawer', type: [{ id: 'Weston Grasscloth' [{diffuse: "image URL", normal: "image URL", metallic: "image URL"}]}]},
    ];

您声明材料错误,因为您不能同时写入一个字符串和列表的值

 type: 'Lacquer' [{ id: 'Astra Blue' <-> [{diffuse: "image URL", normal: "image URL", metallic: "image URL"}]

如果你制作一个console.log(materials)结果是{ id: 1, section: 'Body', type: undefined }

此外,您在同一个 object 中两次声明了id键。

正确的方法应该是:

const materials = [
  {id: 1, section: 'Body', type: 'Lacquer', list0: [{ id: 'Astra Blue', list1: [{diffuse:"image URL", normal: "image URL", metallic: "image URL"}], id1: 'Ballet Pink', list2: [{diffuse: "image URL", normal: "image URL", metallic: "image URL"}]}]},
  {id: 2, section: 'Drawer', type: 'Grasscloth', list0: [{ id: 'Weston Grasscloth', list1: [{diffuse: "image URL", normal: "image URL", metallic: "image URL"}]}]},
];

我为变量选择了随机数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM