在从react组件渲染数据时遇到问题-建议?

时间:2020-09-16 08:41:21

标签: javascript arrays reactjs

我正在研究一个简单的react项目,并试图创建一个产品及其价格表。在ProductRow组件内部,我正在使用forEach()方法遍历我的产品数据并返回产品名称,然后将其呈现在父ProductTable 组件中-除非不是。有什么建议?代码如下:

class FilterableProductTable extends React.Component{
  render(){
    return(
      <div>
        <SearchBar/>
        <ProductTable products = {this.props.products}/>
      </div>
    )
  }
}

class SearchBar extends React.Component{
  render(){
    return(
    <div>
      <input type = 'text' placeholder = 'Search'/>
    </div>
    )
  }
}

class ProductTable extends React.Component{
  render(){
    return(
      <div>
        <table>
          <tr>
            <th>name</th>
            <th>price</th>
          </tr>
        <ProductRow products = {this.props.products}/>
         </table>
      </div>
    )
  }
}

class ProductRow extends React.Component{
  render(){
    const items = this.props.products
    return(
      <tr>
        {
          items.forEach(x=> {
           return <td>{x.name}</td>
          })
        }
      </tr>
    )
  }
}

const PRODUCTS = [
  {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
  {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
  {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
  {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
  {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
  {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];
 
ReactDOM.render(
  <FilterableProductTable products={PRODUCTS} />,
  document.getElementById('container')
);

2 个答案:

答案 0 :(得分:1)

使用map代替forEach

有关详细答案,请参见以下文章:

使用.map(),它会根据给定函数的结果创建一个新数组,而不会损害原始数组。

Dev.to article

Codeburst article

MDN

答案 1 :(得分:1)

使用Map代替forEach,因为它返回一个数组,而forEach不返回任何数组。

  • forEach通常在执行数组循环时使用,可以将其视为for循环的替代物。

  • map创建一个新数组,其中填充了在调用数组中每个元素上调用提供的函数的结果。

class ProductRow extends React.Component{
  render(){
    const items = this.props.products
    return(
      <tr>
        {
          items.map(x=> {
           return <td>{x.name}</td>
          })
        }
      </tr>
    )
  }
}
相关问题