filter vs map reactjs and jsx

后端 未结 3 564
慢半拍i
慢半拍i 2021-01-06 15:45

I\'m working on a react project to learn react.

In a component\'s render method, when I use .map to iterate over values and return an array of component

3条回答
  •  生来不讨喜
    2021-01-06 16:13

    Array.filter does not allow you to transform the data into components. That is the job of Array.map.

    You should instead filter first, then chain the map call afterward:

    {              
      books && books
        .filter(book => book.shelf === shelf)
        .map((book, index) => {
          return (
            
          );
        })
    }
    

    If you want to avoid a second pass over your list of books, you can return null as well, though this is "less good" because you're forcing React to render null when it doesn't need to do any work at all:

    {              
      books && books
        .map((book, index) => {
          if (book.shelf !== shelf) {
            return null;
          }
          return (
            
          );
        })
    }
    

提交回复
热议问题