javascript - ReactJS 中的对象关系?
问题描述
我有一个包含对象的数组,我需要使用其中的键中的值来搜索另一个数组,例如获取项目 ID 的名称。
主数组:
this.setState({ offers: [
{
"name": "Hello World",
"description": "Goodbye World",
"item": {
"value": 1,
"label": "Í'm a label",
"type": 44
},
"action": 2
},
{
"name": "Hello World",
"description": "Goodbye World",
"item": {
"value": 2,
"label": "Í'm a label",
"type": 44
},
"action": 2
},
]});
和项目数组:
this.setState({ items: [
{
"id": 1,
"name": "I'm an item!",
"description": "I'm the item description!"
},
{
"id": 2,
"name": "I'm an item too!",
"description": "I'm the item description too!"
}
]});
在反应中,要显示主数组,我执行以下操作:
render() {
return (
<Col>
{(this.state.offers && this.state.offers.length > 0) ? (
this.state.offers.map(offer => this.renderOffer(offer))
) : (
<p>Loading...</p>
)}
</Col>
);
}
renderOffer(product) {
console.log(product.description) // This would print "Goodbye world"
}
但这只是让我获取主数组的数据,我仍然需要列出每个项目的项目名称/项目描述。我正在寻找类似的东西product.item.name
,它可以从我的第二个数组中获取name
密钥,基于当前在renderOffer
.
如何才能做到这一点?
解决方案
renderOffer()
只需在里面找到与该报价匹配的 id 的项目。
renderOffer(product) {
const item = this.state.items.find(item => item.id === product.item.value)
return (
<ul>
<li>{product.name}</li> // <- Hello World
<li>{item.name}</li> // <- I'm an item!
</ul>
)
}
推荐阅读
- javascript - 使用 apollo/react-hooks 运行查询时出现 400 响应错误代码
- tensorflow - Object Detection API 中的一步是指处理一张图片还是一个边界框?
- gps - 计算 2 个接入点之间的距离
- python-3.x - 如何在 Pandas 中将 Pandas DataFrame 作为附件发送
- php - 如何传递多个数据以在 Laravel 中查看
- python - 无法使用 ElementTree 修改 XML 正文中 CDATA 中的内容
- html - flex 列中的文本省略号
- unicode - 如何将 Ge'ez -1 字体转换为 unicode(power geez unicode)
- laravel - 3 个实体之间的播种机问题
- xamarin.forms - Xamarin 与智能灯集成?