简体   繁体   English

如何在 React 中使用地图内的条件渲染

[英]How to use conditional rendering inside map in React

I have a react page that is rendering a list of products that are being returned from a GraphQL API.我有一个反应页面,它正在呈现从 GraphQL API 返回的产品列表。 Once the products are returned, I'm storing them in a state and then render them.一旦产品返回,我将它们存储在一个状态,然后呈现它们。 How do I only render products that meet certain conditions?如何只渲染满足特定条件的产品?

Right now, I'm mapping over the products and rendering each one.现在,我正在映射产品并渲染每个产品。 This is working correctly.这工作正常。 But if I try to use conditional statements, I get errors in my IDE.但是如果我尝试使用条件语句,我的 IDE 就会出错。 This is the code I currently have.这是我目前拥有的代码。 This is currently working:这是目前工作:

async function contactAPI() {
  return await axios({
    url: 'https://graphqlexample.com/api/products',
    method: 'post',
    data: {
      query: `
      QUERY GOES HERE
        `
    }
  })
}

function App() {  
  const [products, setProducts] = useState([]);

  useEffect(() => {
    async function getData() {
      const res = await contactAPI();
      setProducts(res.data.data.products);
    }
    getData();
  }, []);

  return (
    <div>
        <div>          
          {products.map(p =>           
          (             
          <div>            
            <ProductCard productName={p.productName} />
          </div>
          ))}
        </div>    
    </div>
  );
} 

I need to check p.productName to see if it meet certain conditions, and if it does, render it.我需要检查p.productName以查看它是否满足某些条件,如果满足,则呈现它。 If not, don't render.如果没有,请不要渲染。 I tried using different conditionals inside of map , but keep getting errors.我尝试在map使用不同的条件,但不断出现错误。

As an example you can just return the JSX if it will meet certain criterion as:例如,如果JSX满足特定条件,您可以只返回JSX

Note: For demo purpose I've used includes method.注意:出于演示目的,我使用了includes方法。 You can specify the condition您可以指定条件

(<div><ProductCard productName={p.productName} /></div>)

and will only render if the first condition is true并且只有在第一个条件为true才会呈现

  <div>
    {products.map((p) => (
      p.productName.includes("free") && (<div><ProductCard productName={p.productName} /></div>)
    ))}
  </div>

代码沙盒演示

export default function App() {
  const arr = [1, 2, 3, 4, 5];
  return (
    <div>
      {arr.map((n) => {
        return n % 2 === 0 && <div key={n}>{n}</div>;
      })}
    </div>
  );
}

map will always return an array of the same length so you'll be returning some empty elements depending on the condition which isn't optimal. map将始终返回相同长度的数组,因此您将根据不是最佳的条件返回一些空元素。

Instead filter the data first, and then map over the returned array.而是先filter数据,然后map返回的数组。 That way you're only mapping over the data you need to display.这样,您只需映射需要显示的数据。

 const { useState } = React; function App({ data }) { const [ products, setProducts ] = useState(data); // In this example we take the list of products in // state and return a new array of only those products // that aren't soap. We then `map` over that array in our // component render function getFilteredProducts() { return products.filter(product => { const name = product.productName.toLowerCase(); return !name.includes('soap'); }); } // Get an array of filtered products and then `map` over it // to produce the product cards return ( <div> {getFilteredProducts().map(product => { return ( <ProductCard key={product.id} id={product.id} name={product.productName} /> ); })} </div> ); }; function ProductCard({ id, name}) { return <div>{id}: {name}</div>; } const data=[{id:1,productName:"Blue Soap"},{id:2,productName:"Beans"},{id:3,productName:"Green Soap"},{id:4,productName:"Sponge"},{id:5,productName:"Chicken"}]; ReactDOM.render( <App data={data} />, document.getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

{
    products.map(id => {
      return condition == true ?
        <div>            
          <ProductCard productName={p.productName} />
        </div>
    : <div></div>
})}

 const products = [ { productName: "product1" }, { productName: "product2" }, { productName: "product3" } ]; const App = () => { return ( <div className="App"> <div> {products.map((p, index) => { if (p.productName === "product1") { return <div key={index}>{p.productName}</div>; } return <React.Fragment></React.Fragment>; })} </div> </div> ); } ReactDOM.render( <App />, document.getElementById("react") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="react"></div>

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

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