-3
我從父元素獲取產品數組並嘗試使用forEach遍歷它。相反,我得到一個錯誤「Uncaught TypeError:無法讀取屬性'forEach'未定義在ProductTable.render」。 console.log(行)輸出對象的數組。reactjs無法讀取未定義的屬性'forEach'
下面是我的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'));
謝謝,這是我的一個非常愚蠢的錯誤! – ashish