reactjs - 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)})
}
我已经尝试了很多东西,但没有一个能够保持货架财产的价值。
有没有办法阻止迭代覆盖匹配的值?
任何想法如何达到预期的结果?
预先感谢您的帮助。
解决方案
在您的情况下应该可以正常工作:
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”;
}
});
}
推荐阅读
- symfony - 将 API 平台连接到 Oauth 等外部 SSO
- java - src 文件夹中文件的 intellij 中的 FileNotFoundException 错误
- swift - 更新 Firestore 中文档的某些字段
- wcf - 将值“utf-8”转换为类型“System.Text.Encoding”时出错
- selenium - Selenium 在 for 循环中返回上一页
- amazon-web-services - AWS DynamoDB的分页扫描//必须读取整个表?
- vue.js - 我应该如何避免在平面 vuex 结构中重复数据和 API 调用?
- android - 在 Android 10 及更高版本中使用 MediaStore 保存图像后获取图像信息
- javascript - 来自 firebase 的数据正在以洗牌的方式出现?
- github - 无法在 github 上上传客户端部分