Javascript map()返回不';不在react组件中渲染
我尝试在第二次渲染中渲染数据,并在其上进行JSON数据映射。我必须查看两个对象才能找到匹配的Javascript map()返回不';不在react组件中渲染,javascript,json,reactjs,Javascript,Json,Reactjs,我尝试在第二次渲染中渲染数据,并在其上进行JSON数据映射。我必须查看两个对象才能找到匹配的产品\u id 我做错了什么 { this.props.productGroups.map((productGroup) => { return ( <TabContainer key={productGroup.id}> <h3>{productGroup.title}</h3>
产品\u id
我做错了什么
{
this.props.productGroups.map((productGroup) => {
return (
<TabContainer key={productGroup.id}>
<h3>{productGroup.title}</h3>
{
productGroup.product_ids.map((productId) => {
this.props.products.map((product) => {
if (product.id == productId) {
return (
<div>
test
</div>
)
} else {
console.log('miss')
}
})
})
}
</TabContainer>
)
})
}
{
this.props.productGroups.map((productGroup)=>{
返回(
{productGroup.title}
{
productGroup.product\u ID.map((productId)=>{
this.props.products.map((产品)=>{
if(product.id==productId){
返回(
测试
)
}否则{
console.log('miss')
}
})
})
}
)
})
}
顺便说一句,我知道这是回调地狱,只是不确定重构的最佳方式 您的第一个.map()在this.props…..
返回此.props.products.map((product)=>{
@BenSteward的答案是正确的。请注意,有多种方法可以减少嵌套贴图
一种方法是,不必在产品id
中循环并在产品
中循环,只需在产品
中循环并检查该产品
的id是否存在于指定的产品id中
:
(这是一个更简洁的代码版本,括号和大括号更少)
{
this.props.productGroups.map(productGroup=>(
{productGroup.title}
{this.props.products.map(product=>{
如果(productGroup.product_id.includes(product.id)){/*请注意此行*/
回归试验
}
console.log('miss')
})}
))
}
我相信它的性能会更好,也会让你未来的自己更容易理解。试试这个
productGroup.product\u id.map(函数(productId)
对下一个进行同样的操作,并返回值。如果是旁注,请考虑重新构造产品数据,使其不是产品对象的数组,而是具有密钥产品ID的对象。这意味着您不需要在数组上循环-只需检查产品对象是否包含特定的密钥或密钥不是。这是来自API。@而且在收到数据后,你仍然可以重新构造它。我想这取决于是否让你的生活更轻松。啊哈,谢谢。我也希望得到旁注的答案。你的数据结构是什么样子的?你是如何得到productGroup的?另外,不要担心回调,这就是语言的工作方式我更关心的是一个O(n^2)操作来显示一个数据列表。
{
this.props.productGroups.map(productGroup => (
<TabContainer key={productGroup.id}>
<h3>{productGroup.title}</h3>
{this.props.products.map(product => {
if (productGroup.product_ids.includes(product.id)) { /* Note this line */
return <div>test</div>
}
console.log('miss')
})}
</TabContainer>
))
}