【问题标题】:How to display the content of an array inside an object in Reactjs如何在 Reactjs 中的对象内显示数组的内容
【发布时间】:2020-04-08 08:43:26
【问题描述】:

我有一个 React 组件。当用户进行表单选择时,它会检索以下对象(对象的内容取决于所做的选择):

数据

jsonObj={
 "name":"main",
 "type":"meat",
 "values":[
      ["chicken","Roast chicken with vegetables"],
      ["beef","Beef and Yorkshire pudding"]
]}

期望的结果

这是我想在渲染时在屏幕上显示的内容:

<div>
    <label htmlFor="chicken">Roast chicken and vegetables</label>
</div>
<div>
    <label htmlFor="beef">Beef and Yorkshire pudding</label>
</div>

我的尝试失败了!

Object.entries(jsonObj["values"]).map(([val,index]))=>{
    return(
        <div>
            <label htmlFor={val[index][0]}>{jsonSub[key][1]}:</label>
        </div>
    )
}

这样的结果是:

无法读取未定义的属性“0”。

当我在浏览器控制台中尝试时,我得到“Uncaught SyntaxError: Malformed arrow function parameter list”。有没有人能帮我得到我想要的结果?!

非常感谢!

凯蒂

【问题讨论】:

  • 我不认为map 需要一个数组,那[val,index] 不应该只是val,index 吗? (看起来你可能会在箭头函数以额外的右括号开始之前关闭它)

标签: javascript arrays reactjs object


【解决方案1】:

Object.entries 方法是从对象中获取数组,但是你的“值”已经是数组了,所以直接使用map

jsonObj["values"].map(([html, text]) => (
  <div>
    <label htmlFor={html}>{text}</label>
  </div>
));

【讨论】:

    【解决方案2】:

    你真的不需要Object.entries()。只需在 jsonObj.values 上使用 .map() 并在每次迭代时访问当前元素数组,并为 &lt;label&gt; 显示 e[0]e[1]

    相反,您可以像下面这样更容易地做到这一点:

    jsonObj.values.map(e => {
       return <div>
           <label htmlFor={e[0]}>{e[1]}</label>
       </div>
    });
    

    请看下面的例子:

    const jsonObj = {
     "name":"main",
     "type":"meat",
     "values":[
          ["chicken","Roast chicken with vegetables"],
          ["beef","Beef and Yorkshire pudding"]
    ]}
    
    const result = jsonObj.values.map(e => {
       // just returning a template literal for representation
       return `<label htmlFor="${e[0]}">${e[1]}</label>`;
    });
    
    console.log(result)

    我希望这会有所帮助!

    【讨论】:

    • 感谢 norbitrial 的精彩回答和代码 sn-p!非常感谢您的快速响应:-D
    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2016-01-21
    相关资源
    最近更新 更多