在 reactjs 上使用和不使用箭头功能获取不同的输出 json

Different output fetching json with and without arrow function on reactjs

为什么我在获取 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)
  });

Returns 在控制台上:

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)
  });

Returns这个:

parsing failed TypeError: this is undefined Stack trace:
listCampers/<@http://localhost:3000/static/js/bundle.js:18177:17

arrow function 没有自己的 this 并且引用父 scope(在本例中是 React 组件 )。如果你使用 function 你必须自己设置 this,因为在这种情况下 this指的是全局范围(在浏览器中它是 window)或者如果你使用 strict mode this 将成为 undefined

.then(function(json) {
  this.setState({data: json});
  console.log('parsed json', json)
}.bind(this))
 ^^^^^^^^^^^

是的,因为在第二种情况下

fetch(url)
  .then((response) => {
    return response.json()
  }).then(function(json) {
    this.setState({data: json});    ///The error is given here 
    console.log('parsed json', json)
  }).catch((ex) => {
    console.log('parsing failed', ex)
  });

您正在使用 this.setState 但成功回调未绑定到 React 组件上下文,因此 this 将引用 .then 函数本身的上下文,因此 setState 将不可用

虽然在第一种情况下,this 内部箭头函数指的是父上下文,在您的情况下是 React Component 上下文 其中 setState 可用,因此您得到正确的输出