为什么我在获取 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
最佳答案
arrow function
没有自己的 this
并引用父范围(在本例中它是 React 组件)。如果你使用function
,你必须自己设置this
,因为在这种情况下this
指的是全局范围(在浏览器中是窗口
),或者如果您使用严格模式
this
将是未定义
.then(function(json) {
this.setState({data: json});
console.log('parsed json', json)
}.bind(this))
^^^^^^^^^^^
关于javascript - 在reactjs上使用和不使用箭头函数获取json的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44522894/