reactjs - 我可以从进行 API 调用的数据库中获取数据,然后将其传递给进行另一个 API 调用的另一个函数吗
问题描述
作为反应,我想从数据库中获取数据。我尝试使用 getCoor() 从数据库中获取数据并放入构造函数方法。我定义了变量私有数据:any=[]; 并定义了一个状态 this.state={data:[]}
在这里我试图
- 使用 API 调用从数据库中获取数据
- 使用另一个 API 调用传递此数据。
问题:来自 getCoor 的数据没有存储在我的变量中。
componentDidMount() {
this.defaultCoor();
const Markers = async () => {
await this.getCoor(); // this.data=json;
await this.addGoogleMapScript();//do something with this.data
}
Markers();
}
this.data 为空。我正在尝试等待 getCoor 完成 API 调用,获取数据并传递给 addGoogleMapscript,这在 React 中是否可行?
解决方案
private getCoor() {
const qurl = `/_api/web/lists/getbytitle('${this.props.list}')/items?$select=*&$orderby=Created asc`;
const opt: ISPHttpClientOptions = {
headers: { "Content-Type": "application/json;odata=verbose" }
};
return this.props.spHttpClient
.get(
this.props.context.pageContext.web.absoluteUrl + qurl,
SPHttpClient.configurations.v1,
opt
)
.then((response: SPHttpClientResponse) => {
return response.json().then((json: any) => {
this.setState({ data: json.value });
return (this.data = json);
});
});
}
this.data:any=[]; 在基于类的 React 组件中的构造函数方法之后定义,在 API 函数中添加返回并返回 this.data :)
解决方案
您正在获取数据但未将其分配给变量。为此,您的Markers
函数应如下所示。
componentDidMount() {
this.defaultCoor();
const Markers = async () => {
const data = await this.getCoor(); // this.data=json;
await this.addGoogleMapScript(data); //do something with this.data
}
Markers();
}
推荐阅读
- java - 循环丢失匹配记录时如何显示错误
- python - 如何在 Django 中重用函数或类
- android - 我需要付费 ios 开发者帐户来使用 appium 自动化真实设备和模拟器吗
- java - 多个模块与每个模块在 gradle 中使用 spring 提供休息服务
- ruby-on-rails - 在我调用 api 创建应用程序后获取“FacebookAds::ClientError(无效参数:不接受服务条款(fbtrace_id:Ch/RdwGB+D3))”
- typescript - Onclick 事件添加了动态创建的按钮在 InnerHTML 中不起作用
- python - 如何将“矩阵”转换为“图像”?
- spring-boot - 如何在 Spring Boot 中外部化 application.yml
- jquery - 获取谷歌地图搜索区域内所有标记的列表 - Markerclusterer v3
- c# - 从数据网格c#wpf中获取int值