reactjs - 提示如何在 Reactjs 中渲染时循环
问题描述
我是 Reactjs 的新手并被困在这段代码中,我能够呈现数据,但它为每个产品调用 ProductItem 组件
谁能在不为每个产品调用 ProductItem 的情况下用正确的循环方式提示我
应用程序.js
render() {
return (
<div >
<nav className="navbar navbar-light bg-light">
<span className="navbar-brand mb-0 h1">Product Manager</span>
</nav>
{
this.state.products.map(product => {
return (
<ProductItem
key={product.name}
{...product}
/>
);
})
}
</div>
);
}
ProductItem.js
class ProductItem extends Component {
render(){
const {name, price, quantity} = this.props;
return(
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Product Name</th>
<th>Product Price</th>
<th>Quantity </th>
</tr>
</thead>
<tbody>
<tr>
<td>{name}</td>
<td>{price}</td>
<td>{quantity}</td>
<td><button className="btn btn-danger">Delete</button></td>
</tr>
</tbody>
</table>
</div>
);
}
}
解决方案
不要<ProductItem />
进入循环。this.state.product
你作为<ProductItem />
Like的道具传递:
<ProductItem products={this.state.product} />
然后你的<ProductItem />
组件循环之类的
this.props.products.map((product, index) => {
<tr key={product.index}>
<td>{product.name}</td>
<td>{product.price}</td>
<td>{product.quantity}</td>
<td><button className="btn btn-danger">Delete</button></td>
</tr>
})
在表格 tbody 标签内
推荐阅读
- python - WFDB Plot-Demo 导致 TypeError
- node.js - 根域中的 Index.html 没有在角度 IIS 中获得服务器端渲染
- raspberry-pi - 为什么用杯子打印pdf在树莓派上很慢,比如30秒后开始
- php - Route::get 带参数和重定向
- python - 为什么我在导入时不必指定子模块?
- c# - C# selenium 找不到元素
- angular - 如何在Angular6中使用forkJoin和ngrx进行多个HTTP调用?
- amazon-web-services - AWS Lambda 函数抛出读取超时。(读取超时=60)调用时
- java - Java web start 应用程序不会触发事件
- mysql - 如何将记录选择为单个记录以确定时间差