reactjs无法读取未定义的属性'forEach'

时间:2017-02-24 18:01:35

标签: javascript reactjs foreach react-jsx

我从父元素获取products数组并尝试使用forEach循环遍历它。相反,我得到一个错误“Uncaught TypeError:无法读取属性'forEach'未定义的ProductTable.render”。 console.log(rows)输出对象数组。

下面的

是我的ProductTable组件

import React from 'react';
import ReactDOM from 'react-dom';
import {ProductCategoryRow}  from './productcategoryrow.js';
import {ProductRow} from './productrow.js'

export class ProductTable extends React.Component {    
    render(){
       let rows =[];
       let lastcategory = null;
       this.props.products.forEach(function(product){

            if(product.category !== lastcategory){
                rows.push(<ProductCategoryRow category = {product.category} key={product.category}/>);
            }
            rows.push(<ProductTable product={product} key={product.name}/>);
            lastcategory = product.category;

       });
       console.log(rows);
       return(
           <div>
             <table>
                <thead>
                    <tr>
                        <td>Name</td>
                        <td>Price</td>
                    </tr>

                        {rows}

                </thead>
             </table>
           </div>
        );
    }
}

下面是传递道具的父组件:

import React from 'react';
import ReactDOM from 'react-dom';
import {SearchBar} from './searchbar.js';
import {ProductTable} from './producttable.js';


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

var 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'));

1 个答案:

答案 0 :(得分:2)

forEach循环中,您可以:

<ProductTable product={product} key={product.name}/>

请注意,您正在设置道具productProductTable但是期待道具products

由于变量product的值不是数组,并且由于您未在任何地方使用ProductRow,我只能假设您打算使用

<ProductRow product={product} key={product.name}/>

ProductRow而非ProductTable)代替。