Javascript 数组上未定义映射
所以我尝试迭代并映射这个数组,并从中提取数据。当试图运行代码时,我得到一个错误,说“data.data.children.map(…)。then不是函数”,即使data.data.children是数组。谢谢Javascript 数组上未定义映射,javascript,Javascript,所以我尝试迭代并映射这个数组,并从中提取数据。当试图运行代码时,我得到一个错误,说“data.data.children.map(…)。then不是函数”,即使data.data.children是数组。谢谢 var输出 取('https://www.reddit.com/r/somesubreddit/hot/.json?count=20') .then(response=>response.json()) 。然后(数据=>{ //console.log(data.data.children)
var输出
取('https://www.reddit.com/r/somesubreddit/hot/.json?count=20')
.then(response=>response.json())
。然后(数据=>{
//console.log(data.data.children)
data.data.children.map(命中=>output={
得分:hit.score,
标题:hit.title,
permalink:hit.permalink
})。然后(结果=>{
var done=result.sort(函数(a,b){
返回b.score-a.score
})
这是我的国家({
点击:完成
})
})
}).catch(err=>console.log(err.message));//为了说明错误
Array.prototype.map
不会返回一个承诺
。您不能使用.then()
链接其输出
.map()
应该是同步的,因此不需要使用.then()
。立即使用其输出,如下所示:
var output
fetch('https://www.reddit.com/r/somesubreddit/hot/.json?count=20')
.then(response => response.json())
.then(data => {
console.log(data.data.children)
var result = data.data.children.map(hit => output = {
score: hit.score,
title: hit.title,
permalink: hit.permalink
});
var done = result.sort(function(a, b) {
return b.score - a.score
})
this.setState({
hits: done
})
});
通过链接map
和sort
的输出以删除中间变量,可以进一步简化此过程:
var output
fetch('https://www.reddit.com/r/somesubreddit/hot/.json?count=20')
.then(response => response.json())
.then(data => {
console.log(data.data.children)
var result = data.data.children.map(hit => {
score: hit.score,
title: hit.title,
permalink: hit.permalink
}).sort(function(a, b) {
return b.score - a.score
});
this.setState({
hits: result
})
});
请记住,您只在
fetch()
调用上使用.then()
调用,因为调用是基于承诺的。默认情况下,fetch外部或其回调中的任何实现都不会隐式使用承诺,因此您不能对它们使用.then()
。您有几个错误
。然后方法
output={
…不需要output
变量fetch('https://www.reddit.com/r/somesubreddit/hot/.json?count=20')
.then(response=>response.json())
.then(data=>data.data.children.map({data:{score,title,permalink}})=>({score,title,permalink})))
。然后(结果=>{
var done=result.sort(函数(a,b){
返回b.score-a.score
});
/*
这是我的国家({
点击:完成
});
*/
console.log(完成);
})
您有一个语法错误。您忘记了第1行的=
符号正确,.map
返回一个数组-数组没有。然后方法函数映射来自数组。原型返回一个数组。注意:您的问题标题有误导性…因为它是。然后没有定义