javascript - 在 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 上创建标记
提前致谢。
解决方案
问题是this
在您的匿名函数中未定义。通过分配const that = this
,您可以使上下文componentDidMount()
在所有匿名函数中都可用。另一种解决方案是bind()
使用正确上下文的所有功能。例如
...
.then((function(data) {
this.setState({Data: data.response.groups[0]})
console.log(this.state.Data);
}).bind(this))
...
现在您可以删除that
.
推荐阅读
- c - 替换多个 \t
- java - 从资源加载时 ActionBarDrawerToggle NullPointerException
- ios - Flutter iOS“替换现有签名”“权限被拒绝”错误。命令 PhaseScriptExecution 失败,退出代码非零
- php - Laravel 5.8 多重身份验证
- go - 为什么所有的 goroutines 都睡着了——ticker 死锁了?
- regex - re.search 和链接几个条件,python3
- scala - databricks 中的文件 Snapshot.scala 是什么?
- c# - 没有通过 C# 从我的 SQL Server 数据库中获取我的角色
- python - 安装twisted时出错
- mysql - 如何在 MySQL 查询中使用 IF ELSE 语句选择数据