【问题标题】:Different output fetching json with and without arrow function on reactjsreactjs上带有和不带箭头功能的不同输出获取json
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      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 组件上下文 setState 在哪里可用,因此您会得到正确的输出

      【讨论】:

        猜你喜欢
        • 2021-02-05
        • 2014-03-11
        • 2017-12-25
        • 2016-02-22
        • 2018-08-26
        • 2016-12-22
        • 2016-01-21
        • 1970-01-01
        • 2020-03-28
        相关资源
        最近更新 更多