在ReactJS中获取请求

时间:2018-07-29 17:43:22

标签: javascript reactjs fetch-api

我正在为正在上课的小应用程序工作,而在使用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方法中记录状态时,我的状态为空。

在这一点上,我看到状态设置为“那个”。 但是,如果将其设置为“ that”,我该如何在我的其余应用程序中使用“ this”状态,则我需要此信息来在google maps API上创建标记

提前谢谢。

2 个答案:

答案 0 :(得分:3)

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

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

现在,您可以删除that的声明。

答案 1 :(得分:0)

如果您不太关心IE11支持(并且不使用Babel),请考虑使用arrow functions(这是具有相同{{1}的函数的语法糖) }作为他们周围的this

请注意,string literals与您使用的arrow functions具有相似的兼容性表,因此您不会丢失任何内容并获得更清晰的代码!

带有箭头功能的代码如下:

componentDidMount() {
   /* ... */

   fetch(`URL`)
      .then(response => response.json())
      .then(data => this.setState({Data: data.response.groups[0]}))
      .catch(e => console.log('There is an issue with getting the information' , e))

   /* ... */
}