简体   繁体   English

如何在 React 中迭代组件内的组件

[英]How to iterate over components inside components in React

I have my products components which simply display products, price and description我的产品组件仅显示产品、价格和描述

const Product = (props) =>{
    return(
        <div>
            <p>Price: {props.price} </p>
            <p>Name: {props.name}</p>
            <p>Description: {props.desc}</p>
        </div>
    )
}

Which is rendered by the App component which loops thru the data in productsData and renders a product component for each index in the array.它由 App 组件呈现,该组件循环遍历 productsData 中的数据,并为数组中的每个索引呈现一个产品组件。

class App extends React.Component {

  render() { 
    const products = productsData.map(product => {
      return <Product key={product.id} price={product.price}
      name={product.name} desc={product.description}   />
    })
    return (
      <div>
          {products}
      </div>
    );


  }
}

However, for the sake of learning purposes, I am trying to figure out how I am able to loop thru this array of products components (rendered in App) to only display, for example, prices that are greater than 10 or descriptions that are longer than 10 characters, for example.但是,为了学习目的,我试图弄清楚我如何能够循环通过这一系列产品组件(在 App 中呈现)以仅显示例如大于 10 的价格或更长的描述例如,超过 10 个字符。

productsData looks something like this productsData 看起来像这样

const productsData = [
    {
        id: "1",
        name: "Pencil",
        price: 1,
        description: "Perfect for those who can't remember things! 5/5 Highly recommend."
    },

I am assuming I need to use the.filter method inside the products component, but I can't seem to figure out where.我假设我需要在 products 组件中使用 .filter 方法,但我似乎无法弄清楚在哪里。 I keep getting errors or undefined.我不断收到错误或未定义。 Could someone clear this up, how one would iterate thru components nested inside other components?有人可以澄清这一点,如何通过嵌套在其他组件中的组件进行迭代?

Try this:尝试这个:

 const products = productsData.filter(product => (
  product.price > 10 || product.description.length > 10
)).map(p => (
   <Product key={p.id} price={p.price}
     name={p.name} desc={p.description}   
    />
))

Chaining methods filter with map allows you get the desired result.使用mapChaining方法filter可让您获得所需的结果。

Read more here about filter : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter在此处阅读有关filter的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

You can add a condition in .map , if condition matches then return the Product else return null .您可以在.map中添加条件,如果条件匹配则返回Product ,否则返回null

const products = productsData.map((product) => {
  if (product.price > 10 || product.description.length > 10)
    return (
      <Product
        key={product.id}
        price={product.price}
        name={product.name}
        desc={product.description}
      />
    );
  return null;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM