【发布时间】:2019-06-17 06:30:23
【问题描述】:
我正在尝试学习地图方法。如果我使用这种语法response.data.map(d =>,我可以迭代数据数组并查看结果,但如果我使用这种语法response.data.map(([label, CustomStep]) => {,我会收到以下错误:
Unhandled Rejection (TypeError): Invalid attempt to destructure non-iterable instance
你能告诉我如何解决它,以便我以后自己解决它吗?
在下面提供我的代码sn-p:
axios
.get('http://world/sports/values')
.then(response => {
console.log("sports--->", response.data.map(d => d.customFieldValueName));
//this.setState({ playerRanks: response.data.map(d => d.customFieldValueName) });
// es6 map
//Unhandled Rejection (TypeError): Invalid attempt to destructure non-iterable instance
this.setState({
playerRanks: response.data.map(([label, CustomStep]) => {
label.customFieldValueName
})
})
})
更新 1:
嘿,我在控制台看到,data是一个数组,里面有这么多对象
data: Array(19)
[
{
"customFieldValueCode": "player1",
"customFieldValueName": "player1",
"isActive": "Y"
},
{
"customFieldValueCode": "player 2",
"customFieldValueName": "player 2",
"isActive": "Y"
}
]
【问题讨论】:
-
您希望收到的数据的结构是什么?您只能使用
[]来解构数组或可迭代对象;你可以使用{}来解构一个对象。 -
你应该检查
console.log(JSON.stringify( response.data,undefined,2))的输出错误类似于const [a,b]=22 -
@HMR 嘿,你能告诉为什么你在控制台中使用 undefined 和 2,我可以在控制台中看到这一行的值
console.log(JSON.stringify( response.data,undefined,2)) -
@HMR 和我对这种
console.log()格式所做的工作通常使您正在记录的对象的完整(或者更确切地说是所需的)深度可见。使用现代浏览器 console.log(someObj) 因为它允许您在“开发工具”控制台中检查整个对象,但在服务器端环境中console.log()只会给你[Object]并使用 @将对象转换为字符串的 987654334@ 仍然只会显示该对象的“拳头”级别...... -
@cantuke 我使用 JSON.stringify 是因为即使在浏览器中,当您展开已记录的对象时,它也会显示现在的对象;不像在记录时那样(您可能已经改变了对象以适应或破坏靠近日志的代码)例如:
const arr = [{name:'Ben'}];console.log(arr);arr[0].name='Jerry';当您展开记录的对象时,它显示名称是 Jerry 但那不是记录时的名称。JSON.stringify(obj,undefined,2)中的 2 是用于格式化 JSON 的制表符大小的空格数。
标签: javascript ecmascript-6 axios