简体   繁体   English

ReactJs:如何 map 和 object

[英]ReactJs: How to map an object

I get data(object) while fetching user info from API.我从 API 获取用户信息时获取数据(对象)。 It quite looks like,很像,

{
    "id":"1111",
    "name":"abcd",
    "xyz":[
        {
            "a":"a",
            "b":"b",
            "c":"c"
        },
        {
            "a":"e",
            "b":"f",
            "c":"g"
        }
    ],
    "email":"abc@xyz.com",
    "phone":"0123456789"
}

here I store(JSON response) the data by using useState hook.在这里,我使用useState挂钩存储(JSON 响应)数据。 Now I can easily access any index by typing data.id or data.name, But the problem is if I map data.xyz like that现在我可以通过输入 data.id 或 data.name 轻松访问任何索引,但问题是如果我像这样的 map data.xyz

(data.xyz).map((xyz,index) => (//something)

it says,它说,

TypeError: Cannot read property 'map' of undefined

I use Object.keys(data.xyz).map as this is an object but not working.我使用Object.keys(data.xyz).map因为这是一个 object 但不起作用。 How can I access/loop through xyz index?如何访问/循环通过 xyz 索引?

How do you initialize the data?如何初始化数据? When you fetch to API, this is an async event, so probably in the first render data.xyz is undefined.当您获取到 API 时,这是一个异步事件,因此可能在第一次渲染中 data.xyz 未定义。 Maybe you can do:也许你可以这样做:

const [data, setData] = useState({ xyz: [] });

 let data = { id: "1111", name: "abcd", xyz: [ { a: "a", b: "b", c: "c", }, { a: "e", b: "f", c: "g", }, ], email: "abc@xyz.com", phone: "0123456789", }; let xyz = data.xyz.map((xyz, index) => { console.log(xyz); return xyz; }); console.log("XYZ ==>", xyz);

Let me guess you have defined data as follow:让我猜你定义的数据如下:

class SomeClass {
  data: {
    "id":"1111",
    "name":"abcd",
    "xyz":[
        {
            "a":"a",
            "b":"b",
            "c":"c"
        },
        {
            "a":"e",
            "b":"f",
            "c":"g"
        }
    ],
    "email":"abc@xyz.com",
    "phone":"0123456789"
  }
}

Instead of doing this:而不是这样做:

class SomeClass {
  data = {
    "id":"1111",
    "name":"abcd",
    "xyz":[
        {
            "a":"a",
            "b":"b",
            "c":"c"
        },
        {
            "a":"e",
            "b":"f",
            "c":"g"
        }
    ],
    "email":"abc@xyz.com",
    "phone":"0123456789"
  }
}

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

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