过滤器与地图reactjs和jsx [英] filter vs map reactjs and jsx

查看:51
本文介绍了过滤器与地图reactjs和jsx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个React项目,以学习React.

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

在组件的render方法中,当我使用 .map 遍历值并返回组件数组时,一切都会按预期进行.

In a component's render method, when I use .map to iterate over values and return an array of components, everything works as expected.

<ol className="books-grid">
        {              
          books && books.map((book, index) => {
            if (book.shelf === shelf) {
              return (
                <Book key={book && book.id ? book.id : index} changeShelf={this.props.changeShelf} book={book} />
              );
            }
          })}
      </ol>

但是当我使用 filter 时:

<ol className="books-grid">
            {              
              books && books.filter((book, index) => {
                if (book.shelf === shelf) {
                  return (
                    <Book key={book && book.id ? book.id : index} changeShelf={this.props.changeShelf} book={book} />
                  );
                }
              })}
          </ol>

我得到了错误(我已经研究过)

I get the error (which I've researched)

未捕获(承诺)错误:对象作为React子对象无效

我不明白为什么 filter map 抛出此错误?是否有独特的反应和 .map ?两者都返回一个数组.

I don't understand why filter is throwing this error vs map? Is there something unique to react and .map? Both return an array.

推荐答案

Array.filter 不允许您将数据转换为组件.那就是 Array.map 的工作.

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 (
        <Book
           key={book && book.id ? book.id : index}
           changeShelf={this.props.changeShelf}
           book={book} />
      );
    })
}

如果您想避免第二遍遍您的 books 列表,则也可以返回 null ,尽管这样做不太好",因为您强迫在根本不需要做任何工作的情况下做出反应以渲染 null :

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 (
        <Book
           key={book && book.id ? book.id : index}
           changeShelf={this.props.changeShelf}
           book={book} />
      );
    })
}

这篇关于过滤器与地图reactjs和jsx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆