我正在为我正在学习的类(class)开发一个小型应用程序,但在使用 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”。 但是,如果它设置为“that”,我如何在应用程序的其余部分使用“this”状态,我需要此信息在谷歌地图 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
的声明。
关于javascript - 在 ReactJS 中获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582951/