动态生成 through a function in React

问题描述 投票:0回答:1

我有以下函数,当我们映射元素时应该返回<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语句。

reactjs
1个回答
1
投票

你想要返回的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.
}
© www.soinside.com 2019 - 2024. All rights reserved.