首页 > 解决方案 > 从反应组件呈现数据时遇到问题 - 建议?

问题描述

我正在做一个简单的反应项目,并试图创建一个产品表及其各自的价格。在我的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')
);

标签: javascriptarraysreactjs

解决方案


使用map而不是forEach.

详细答案请看以下文章:

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

Dev.to 文章

Codeburst 文章

MDN


推荐阅读