如何在获取 API 调用结果中使用“this”关键字

Har*_*h S 4 javascript reactjs fetch-api react-redux

我正在使用以下获取 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 });
  });
Run Code Online (Sandbox Code Playgroud)

sup*_*a28 6

您可以使用箭头函数

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

或者您可以将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 });
  });
Run Code Online (Sandbox Code Playgroud)