首页 > 解决方案 > 提示如何在 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>
                );
            }
        }

标签: reactjscrud

解决方案


不要<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 标签内


推荐阅读