【发布时间】:2017-11-15 07:32:47
【问题描述】:
为什么我在获取 json 时得到不同的响应?当我使用箭头功能时它有效,当我不使用时它不起作用。
constructor(props){
super(props);
this.state = {
data: [],
};
this.url = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent';
}
使用箭头函数获取:
fetch(url)
.then((response) => {
return response.json()
}).then((json) => {
this.setState({data: json});
console.log('parsed json', json)
}).catch((ex) => {
console.log('parsing failed', ex)
});
在控制台返回:
parsed json Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 90 more… ]
当我不使用箭头函数时,输出是不同的:
fetch(url)
.then((response) => {
return response.json()
}).then(function(json) {
this.setState({data: json});
console.log('parsed json', json)
}).catch((ex) => {
console.log('parsing failed', ex)
});
返回这个:
parsing failed TypeError: this is undefined Stack trace:
listCampers/<@http://localhost:3000/static/js/bundle.js:18177:17
【问题讨论】:
标签: javascript json reactjs parsing fetch