![](/img/trans.png)
[英]How to loop through array of objects and create a new array of objects with only certain properties using typescript and react?
[英]How to loop through properties of objects inside of an array within a React component?
這是我的父組件的渲染函數:
render() {
const users = [
'tom': {
phone: '123',
email: 'hotmail'
},
'rob': {
phone: '321',
email: 'yahoo'
},
'bob': {
phone: '333',
email: 'gmail'
},
];
const list = users.map((user) =>
(<User
name={user}
phone={users.phone}
email={users.email}
/>),
);
return <ul>{list}</ul>;
}
輸出顯示如下:
這是Child組件的render函數:
render() {
const {
name,
phone,
email,
} = this.props;
const info = [name, phone, email];
const item = info.map((index) => (
<li key={index}>
{ index }
</li>
));
return item;
}
如何獲得與電話號碼和電子郵件一起顯示的信息? 不知道我做錯了什么。 謝謝。
首先,這是無效的javascript:
const users = [
'tom': {
phone: '123',
email: 'hotmail'
},
// ...
];
您應該定義一個數組或一個對象。 假設您的users
是一個對象文字:
const users = {
'tom': {
phone: '123',
email: 'hotmail'
},
// ...
};
然后,您可以遍歷對象的條目 :
const list = Object.entries(users).map(([name, info]) =>
(<User
name={name}
phone={info.phone}
email={info.email}
/>)
);
但是並非所有瀏覽器都支持Object.entries()
,請檢查它是否在您的環境中有效。
首先是users
不是有效的數組。如果要在主作用域中使用鍵值對,請使用Object
({})
render() {
const users = {
'tom': {
phone: '123',
email: 'hotmail'
},
'rob': {
phone: '321',
email: 'yahoo'
},
'bob': {
phone: '333',
email: 'gmail'
},
};
const list = Object.keys(users).map((user) =>
(<User
name={user}
phone={users[user].phone}
email={users[user].email}
/>),
);
return <ul>{list}</ul>;
}
您需要在父組件的地圖功能中引用“用戶”而不是“用戶”。 “用戶”變量的目的是代表數組中每個元素的當前實例。 因此,地圖功能應如下所示:
const list = users.map((user) =>
(<User
name={user}
phone={user.phone}
email={user.email}
/>),
);
代替。
一種解決方案是將“列表”更改為實際列表:
const users = [
{
name: 'tom',
phone: '123',
email: 'hotmail'
},
{
name: 'rob,
phone: '321',
email: 'yahoo'
},
{
name: 'bob',
phone: '333',
email: 'gmail'
},
];
現在是用戶user.name
而不是user
。
或者,創建一個由每個用戶的名稱作為鍵的對象:
const users = {
'tom': {
phone: '123',
email: 'hotmail'
},
'rob': {
phone: '321',
email: 'yahoo'
},
'bob': {
phone: '333',
email: 'gmail'
},
};
然后映射鍵:
const list = Object.keys(users).map((user) =>
(<User
name={user}
phone={users[user].phone}
email={users[user].email}
/>),
);
您的const用戶應進行修改以通過他們進行映射。
const users = [
{
name: 'tom',
phone: '123',
email: 'hotmail',
},
{
name:'rob',
phone: '321',
email: 'yahoo'
},
{
name: 'bob',
phone: '333',
email: 'gmail'
},
];
const list = users.map((usr =>
(<User
name={usr.name}
phone={usr.phone}
email={usr.email}
/>),
);
return <ul>{list}</ul>;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.