javascript - 在reactjs上使用和不使用箭头函数获取json的不同输出

标签 javascript json reactjs parsing fetch

为什么我在获取 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/

相关文章:

javascript - 如何在 iPad 和 iPhone 上完美显示全屏谷歌地图?

javascript - 使用 Canvas 和 JavaScript 进行多边形表示的图像采样算法?

javascript - 组合多个 jQuery 脚本

sql - 如何在postgresql中将两行转换为键值json对象?

javascript - Jquery Scroll 从用户在屏幕上的任何地方滚动一个像素

jquery - 如何使用 jQuery 动态添加超链接?

javascript - 从 JSF 访问 Javascript 变量

reactjs - 我怎样才能从 React beautiful dnd 中组合起来处理我的项目?

javascript - Redux-saga如何向saga内部请求传递参数

javascript - react native 元素复选框