ReactJS通过Object映射 [英] ReactJS map through Object

查看:94
本文介绍了ReactJS通过Object映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的回复:

我想在此HTML中显示每个对象的名称:

I want to display the name of each object inside this HTML:

{subjects.map((item, i) => (
  <li className="travelcompany-input" key={i}>
    <span className="input-label">{ item.name }</span>
  </li>
))}   

但它会引发错误 subjects.map不是函数

首先,我必须定义它所在对象的键创建一个键数组,我想循环并显示 subject.names

First, I have to define the keys of the objects where it creates an array of keys, where I want to loop through and show the subject.names.

我也是试过这个:

{Object.keys(subjects).map((item, i) => (
  <li className="travelcompany-input" key={i}>
    <span className="input-label">key: {i} Name: {subjects[i]}</span>
  </li>
))}


推荐答案

致电 Object.keys 它返回对象键的数组。

When calling Object.keys it returns a array of the object's keys.

Object.keys({test :'',test2:''})// ['test','test2']

当你打电话给 Array.map 该函数接受2个参数; 1.项目,2。索引。

When you call Array.map the function takes in 2 arguments; 1. the item, 2. the index.

当你想获得数据时,你需要使用 item 而不是

When you want to get the data, you need to use item instead of i

{Object.keys(subjects).map((keyName, i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">key: {i} Name: {subjects[keyName]}</span>
    </li>
))}

这篇关于ReactJS通过Object映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆