简体   繁体   English

React函数在正确结果之上返回未定义

[英]React function returning undefined on top of correct results

I have a function that is looping over one array, comparing it with the results in another and on finding a matching result, adds the matches to a new array, addToState and concatenates these results with the original array having changed the shelf value ready to be rendered. 我有一个循环遍历一个数组的函数,将其与另一个数组中的结果进行比较,然后找到匹配的结果,将匹配项添加到新数组, addToState并将这些结果与已更改shelf值的原始数组连接起来呈现。

All well and good. 一切都很好。

The problem I have is that for some reason the addToState array as well as having the two correct results has a further 18 values of undefined . 我的问题是,由于某种原因, addToState数组以及两个正确的结果还具有undefined的另外18个值。

Why are these being added in and what can I do to prevent this? 为什么要添加这些,我该怎么做才能防止这种情况?

My function: 我的功能:

updateExistingShelves(searchResults) {
        const books = this.props.books
        const addToState = searchResults.map((result) => books.find(b => {
          if(b.id === result.id) {
            result.shelf = b.shelf
            return result
          }
        }))
        console.log(addToState) 
        books.concat(addToState)
        return searchResults
     }

addToState end value: addToState最终值:

(20) [{…}, {…}, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
0
:
{title: "The Hatred of Poetry", authors: Array(1), publisher: "FSG Originals", publishedDate: "2016-06-07", description: "No art has been denounced as often as poetry. It's… vocation no less essential for being impossible.", …}
1
:
{title: "A Poetry Handbook", authors: Array(1), publisher: "Houghton Mifflin Harcourt", publishedDate: "1994", description: "Offers advice on reading and writing poetry, and d… verse, diction, imagery, revision, and workshops", …}
2
:
undefined
3
:
undefined
4
:
undefined
5
:
undefined
6
:
undefined
7
:
undefined
8
:
undefined
9
:
undefined
10
:
undefined
11
:
undefined
12
:
undefined
13
:
undefined
14
:
undefined
15
:
undefined
16
:
undefined
17
:
undefined
18
:
undefined
19
:
undefined
length
:
20

You can use a variable with a greated scope and save the found items into it and use forEach intead of map for this. 您可以使用范围扩大的变量,并将找到的项目保存到其中,并为此使用map的forEach inad。

 updateExistingShelves(searchResults) {
        const books = this.props.books;
        let filteredResult=[];
        searchResults.forEach((result) => books.find(b => {
          if(b.id === result.id) {
            let temp = {...result};
            temp.shelf = b.shelf
            filteredResult.push(temp)
          }
        }))
        console.log(filteredResult) 
        books.concat(filteredResult)
        return searchResults
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM