【问题标题】:How to use "this" keyword inside a fetch API call result如何在 fetch API 调用结果中使用“this”关键字
【发布时间】:2018-11-04 12:00:55
【问题描述】:

我正在使用以下 fetch API 来获取 API 结果。我需要在状态中设置结果数据,但回调函数中的“this”对象不可用。如何通过访问this 关键字来更新代码以设置状态值?

fetch(config.apiUrl + '/api/user', {
  headers: authHeader(),
  method: 'GET',
})
  .then(function(res) {
    return res.json();
  })
  .then(function(data) {
    this.setState({ id: data.id });
  });

【问题讨论】:

  • 这个问题是用 react-redux 标记的,所以如果你使用 Redux,以这种方式改变状态是不寻常的。在 Redux 中,您可能会将新状态连接到 reducer 中的全局状态存储,而不是在上下文中改变 UI React 状态(this)。 Redux 通过使用 'this' 作为可变状态存储解决了出现的上下文复杂性。不是答案,只是观察。

标签: javascript reactjs react-redux fetch-api


【解决方案1】:
  • this 关键字分配给在回调之外仍然可用的变量。经常使用var self = this;
  • 在需要的回调中使用“self”。

【讨论】:

    【解决方案2】:

    你可以使用箭头函数

    fetch(config.apiUrl + '/api/user', {
      headers: authHeader(),
      method: 'GET',
    })
      .then(res => {
        return res.json();
      })
      .then(data => {
        this.setState({ id: data.id });
      });
    

    或者您可以将 this 关键字分配给变量并使用它 var that = this;

    fetch(config.apiUrl + '/api/user', {
      headers: authHeader(),
      method: 'GET',
    })
      .then(function(res) {
        return res.json();
      })
      .then(function(data) {
        that.setState({ id: data.id });
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多