我有以下函数,当我们映射元素时应该返回<tr>
:
renderProductRow = () => {
let table;
for(let product in this.props.productProgressInfo){
productName.push(this.props.productProgressInfo[product]);
}
//productName is an array that simply holds the name of the products
productName.map((name:any)=> {
table = <tr>
<td>Product</td>
<td>{name}</td>
<td>{this.props.siteStatusQueued}</td>
</tr>
return table;
})
return table;
}
return table;
}
在我的render()
回复声明中,我打电话给this.renderProductRow()
。当它触发时,我可以看到1行被渲染一瞬间然后消失。我的猜测是我在某种程度上弄乱了函数中的return语句。
你想要返回的map
的结果是一个数组,但是你没有存储结果。使用table
作为变量令人困惑,因为在map函数退出后,它将保持设置为productName中最后一个条目生成的值。
看起来你的意思是这样做:
renderProductRow = () => {
if (<condition>) {
for(let product in this.props.productProgressInfo){
productName.push(this.props.productProgressInfo[product]);
}
return productName.map((name:any)=> {
return (<tr>
<td>Product</td>
<td>{name}</td>
<td>{this.props.siteStatusQueued}</td>
</tr>)
}) }
else
{return null} // or return an empty array [] depending on what parent component expects.
}