gpt4 book ai didi

javascript - ReactJS无法读取未定义的属性 'forEach'

转载 作者:行者123 更新时间:2023-11-28 18:06:33 27 4
gpt4 key购买 nike

我正在从父元素获取产品数组,并尝试使用 forEach 循环遍历它。相反,我收到错误“未捕获类型错误:无法读取 ProductTable.render 中未定义的属性“forEach””。 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>
);
}
}

下面是传递 props 的父组件:

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

最佳答案

forEach内循环你所做的:

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

请注意,您正在设置属性 productProductTable但是期望 Prop product<strong><em>s</em></strong> .

由于变量的值 product不是数组,因为您没有使用 ProductRow在任何地方我只能假设你打算使用

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

( ProductRow 而不是 ProductTable )。

关于javascript - ReactJS无法读取未定义的属性 'forEach',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42445381/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com