首页 > 解决方案 > React.JS:嵌套过滤器/映射数组

问题描述

我正在尝试将 React 作为我正在使用 Udacity 进行的课程的一部分来学习。我已经与这个问题斗争了几天,似乎无法摆脱它。

基本上,我有一个 API 调用,它返回一个对象数组作为承诺,我映射或过滤这些对象(我都尝试过),并且需要找到数组中已经存在的元素booksOnShelves。我通过比较.id每个对象的属性来做到这一点。一旦我们找到匹配项,我需要将.shelf属性设置为与现有数组中的值相同的值,如果这本书不存在,我需要将其值设置为'none'. 这里一切都很好,但问题是当我找到匹配项时,属性会更新shelf为正确的,但迭代会继续下一本显然不匹配的书,并.shelf用 none 覆盖该值。

这是此特定方法的代码:

class SearchBar extends Component {
  state = {
    query: '',
    result: []
  }

  getBooks = (query) => {
    const booksOnShelves = this.props.books;

    BooksAPI.search(query)
    .then(res => {
      if (res instanceof Array && res.length > 0) {
        res.filter( searchedBooks => {
          return booksOnShelves.filter( onShelves => {
            if ( searchedBooks.id === onShelves.id) {
              return searchedBooks.shelf = onShelves.shelf
            } else {
              return searchedBooks.shelf = 'none
            }
          })
        })
        this.setState({result: res.sort(sortBy('title'})
      } else {
        this.setState({result: []})
      }
    })
    .catch( err => { console.log('ERROR: ', err)})
  }

我已经尝试了很多东西,但没有一个能够保持货架财产的价值。

有没有办法阻止迭代覆盖匹配的值?

任何想法如何达到预期的结果?

预先感谢您的帮助。

标签: reactjs

解决方案


在您的情况下应该可以正常工作:

BooksAPI.search(query).then(res => {
if (res instanceof Array && res.length > 0) {
  booksOnShelves.forEach((book) => {
    const correspondingRes = res.find((item) => { return (item.id === book.id) });
    if (correspondingRes) {
      book.shelf = correspondingRes.shelf;
    } else {
      book.shelf = “none”;
    }
  });
}

推荐阅读