首页 > 解决方案 > 我可以从进行 API 调用的数据库中获取数据,然后将其传递给进行另一个 API 调用的另一个函数吗

问题描述

作为反应,我想从数据库中获取数据。我尝试使用 getCoor() 从数据库中获取数据并放入构造函数方法。我定义了变量私有数据:any=[]; 并定义了一个状态 this.state={data:[]}

在这里我试图

问题:来自 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 :)

标签: reactjsspfxreact-lifecycle

解决方案


您正在获取数据但未将其分配给变量。为此,您的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();
}


推荐阅读