前言:我仍在习惯 ES6 并通过在线类(class)开发我的第一个 React 应用程序。我将在这里与任何愿意深入研究的人分享我的问题和我的 git 存储库。该应用程序允许您搜索和整理不同类别的书籍。
错误:
Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined
at Object.mergeShelfAndSearch (BookUtils.js:22)
at Search.js:41
BookUtils.js
将几个函数导出到 React 组件(不确定它是如何知道去哪里的,但它可以工作)。 Search.js
组件处理搜索功能。在测试时,我将搜索不存在的内容(即“zzzzz”)。当我输入我知道存在的内容时,我会收到上述错误。
BookUtils.js
中的代码:
export const mergeShelfAndSearch = (shelf, search) => {
const hashTable = {};
shelf.forEach(book => hashTable[book.id] = book.shelf);
search.forEach(book => {
book.shelf = hashTable[book.id] || 'none';
});
return search;
}
错误是 'shelf.forEach'。
Search.js 中的代码:
updateSearch = () => {
if (this.state.query === "") {
this.setState({ error: false, books: [] });
return;
}
BooksAPI.search(this.state.query).then(response => {
let newList = [];
let newError = false;
if (response === undefined || (response.error && response.error !== "empty query")) {
newError = true;
} else if (response.length) {
newList = BookUtils.mergeShelfAndSearch(this.props.selectedBooks, response);
newList = BookUtils.sortAllBooks(newList);
}
this.setState({ error: newError, books: newList });
})
}
错误出现在来自 BookUtils.js
的带有“mergeShelfAndSearch”的 else if 语句中。我试过将“shelf”设置为全局变量,但仍然出现错误,我觉得我已经把 console.log(shelf);到处都没有运气。如果有人足够好奇,下面是我的 repo 协议(protocol)的链接。谢谢!
https://github.com/alecb513/reactnd-project-myreads-starter-master
最佳答案
改变
else if (response.length) {
newList = BookUtils.mergeShelfAndSearch(this.props.selectedBooks, response);
newList = BookUtils.sortAllBooks(newList);
}
到
else if (response.length) {
newList = BookUtils.mergeShelfAndSearch(Array.isArray(this.props.selectedBooks) ? this.props.selectedBooks: [], response);
newList = BookUtils.sortAllBooks(newList);
}
或者
else if (response.length && Array.isArray(this.props.selectedBooks)) {
newList = BookUtils.mergeShelfAndSearch(Array.isArray( this.props.selectedBooks, response);
newList = BookUtils.sortAllBooks(newList);
你得到 .forEach 的原因是未定义的,因为最初 this.props.selectedBooks 可能是未定义的或 null 或一个对象。所以在它上面做 .forEach 会抛出一个错误。因此,要解决此问题,请检查它是否为数组,然后再将 this.props.selectedBooks 传递给 mergeShelfAndSearch 函数。还要确保从父组件向 selectedBooks 发送数据数组
关于javascript - 函数参数可以使用数组方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53347523/