首页 > 解决方案 > 在 ReactJS 中获取请求

问题描述

我正在为我正在学习的课程开发一个小型应用程序,并且在使用 fetch API 时遇到问题

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      map: "",
      markers: [],
      Data: []
    };
  }

  componentDidMount() {
    fetch(
      `https://api.foursquare.com/v2/venues/explore?near=ashkelon&v=20180729&client_id=MVLZGLPIAITJITM0OOFYER3C2ZRT5ERGGEWCC0T1YWV3HFZA&client_secret=1TBLTY0TSM1T320FEO3BJBGTMYVQPCMBOGO5GEBC0ZB1E5LK`
    )
      .then(function(response) {
        return response.json();
      })
      .then(
        function(data) {
          this.setState({ Data: data });
        }.bind(this)
      )
      .catch(function(e) {
        console.log("There is an issue with getting the information", e);
      });
  }
}

window.initMap = this.initMap;
loadJS("https://maps.googleapis.com/maps/api/js?key=AIzaSyDySeqpuOjQlckWJUMlbSW_w5CydOVTWJI&callback=initMap");

更新:这不会提供错误并且状态已设置,但现在发生的是当我在 initMap 方法中记录状态时我的状态为空。

在这一点上,我看到状态设置为“那个”。但是,如果它设置为“那个”,我如何在我的应用程序的其余部分使用“这个”状态,我需要这些信息来在谷歌地图 API 上创建标记

提前致谢。

标签: javascriptreactjsfetch-api

解决方案


问题是this在您的匿名函数中未定义。通过分配const that = this,您可以使上下文componentDidMount()在所有匿名函数中都可用。另一种解决方案是bind()使用正确上下文的所有功能。例如

...
.then((function(data) {
    this.setState({Data: data.response.groups[0]})
    console.log(this.state.Data);
}).bind(this))
...

现在您可以删除that.


推荐阅读