首页 > 解决方案 > 我们如何比较每个元素数组并根据值显示元素

问题描述

我有一个要显示标题和行值的表格,行值将从 API 中获取,而头值将被硬编码。

但是我们不会根据每一行的 prop 值显示一列。即 this.props.members[行数组].show_col_volume = true。

所以我已经使用下面的代码为所有行映射了 show_col_volume 并存储在一个变量中

现在我们每行都有布尔项的体积变量数组。然后通过迭代 forEach 我正在检查每个索引并编写显示条件

const volume=  this.props.members.map((val, i) => {
      if(val.show_volume_column === true){
             return true
           }
        else{
          return false;
        }
  });

<span style={{ width: '40%' }}><FormattedMessage {...messages.tableDetailsHeadPremiumLabel} /></span>
 //If the particular index of row has true then we need to display the corresponding column else we will not be displaying

  {volume.forEach(function(show){
     console.log(show,"show")
     if(show === true){
           return  <span style={{ width: '20%' }}><FormattedMessage {...messages.tableDetailsHeadVolumeLabel} /></span>;
     }
     else{
       return null
     }
   })}

//Place where table rows are displayed
</thead><tbody>{rows}</tbody></Table>
  }

我的问题是针对所有情况,即使特定的索引行值为真,但我无法看到显示的列

标签: javascriptreactjs

解决方案


尝试这个:

  return this.props.members.map(member => {    
    return (member.show_volume_column && (
        <span style={{ width: "20%" }}>
          <FormattedMessage {...messages.tableDetailsHeadVolumeLabel} />
        </span>
    ))
  });

推荐阅读