Javascript 如何在ReactJS中的组件之前加载数据?

Javascript 如何在ReactJS中的组件之前加载数据?,javascript,function,reactjs,google-analytics,Javascript,Function,Reactjs,Google Analytics,我的项目目的是从谷歌分析API获取数据,并将所有数据显示为列表。我可以成功地从API获取数据。我正在将数据传递给另一个组件。我可以看到数据是控制台,但是当我试图将它们加载到组件中时,我什么也得不到。 我的第一个组件如下所示: class TabsExample extends Component { constructor(props) { super(props); this.handleLoad = this.authorize.bind(this);

我的项目目的是从谷歌分析API获取数据,并将所有数据显示为列表。我可以成功地从API获取数据。我正在将数据传递给另一个组件。我可以看到数据是控制台,但是当我试图将它们加载到组件中时,我什么也得不到。 我的第一个组件如下所示:

class TabsExample extends Component {
      constructor(props) {
       super(props);
       this.handleLoad = this.authorize.bind(this);
       this.handleProfiles = this.handleProfiles.bind(this);
       this.arr = [];
       this.state = {
        info: [],
        details: []
       }
     }

    componentDidMount() {
     window.addEventListener('load', this.handleLoad);
    }

    handleAccounts = (response) => {
     var details = response.result.items;
     console.log(response)
     this.setState({
      info: details
     });
     details.map(x => {
      gapi.client.analytics.management.webproperties.list(
        { 'accountId': x.id })
        .then(this.handleProperties)
        .then(null, function (err) {
          console.log(err);
        })
      })
     }

    handleProperties = (response) => {
      // Handles the response from the webproperties list method.
      if (response.result.items && response.result.items.length) {

      // Get the first Google Analytics account
      var firstAccountId = response.result.items[0].accountId;

      // Get the first property ID
      var firstPropertyId = response.result.items[0].id;

      // Query for Views (Profiles).
      this.queryProfiles(firstAccountId, firstPropertyId);
      //console.log(firstPropertyId)
    } else {
      console.log('No properties found for this user.');
     }
    }

    queryProfiles = (accountId, propertyId) => {
    // Get a list of all Views (Profiles) for the first property
    // of the first Account.
    gapi.client.analytics.management.profiles.list({
      'accountId': accountId,
      'webPropertyId': propertyId
    })
      .then(this.handleProfiles)
      .then(null, (err) => {
        // Log any errors.
        console.log(err);
      })
    }

     handleProfiles(response) {
    // Handles the response from the profiles list method.
    if (response.result.items && response.result.items.length) {
      // Get the first View (Profile) ID.
      var firstProfileId = response.result.items[0].id;

      // Query the Core Reporting API.
      //console.log(firstProfileId);
      //this.queryCoreReportingApi(firstProfileId);
      gapi.client.analytics.data.ga.get({
        'ids': 'ga:' + firstProfileId,
        'start-date': '30daysAgo',
        'end-date': 'today',
        'metrics': 'ga:sessions, ga:bounces, ga:users'
      })
        .then((response) => {
          // this.setState({
          //   details: [this.state.details, response]
          // })
          this.arr.push(response)
        })
    } else {
      console.log('No views (profiles) found for this user.');
    }
    }

    queryCoreReportingApi(profileID) {
     console.log(profileID);
    }

    authorize = (event) => {
    var useImmidiate = event ? false : true;
    var authData = {
      client_id: CLIENT_ID,
      scope: SCOPES,
      immidiate: useImmidiate
    };
    gapi.auth.authorize(authData, (response) => {
      gapi.client.load('analytics', 'v3').then(() => {
        //console.log(response);
        gapi.client.analytics.management.accounts.list()
          .then(this.handleAccounts);
      });
    });
    }

    render() {
    return (
      <Tabs>
        <Tab label="Accounts" >
          <div>
            <NewsList info={this.arr} />
            {this.arr}
          </div>
        </Tab>
        <Tab label="Visual Data" >
          <div>
            <h2 className='tab_headline'>Tab Two</h2>
            <div className="row">
              <div className="col-md">
                <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Pie_chart_EP_election_2004.svg/1280px-Pie_chart_EP_election_2004.svg.png"
                  alt="First"
                  className="img-thumbnail"
                  style={divHeight} />
              </div>
              <div className="col-md">
                <img src="https://confluence.atlassian.com/fisheye/files/298976800/299139805/3/1484820924815/FishEye_Charts_Page02.png"
                  alt="First"
                  className="img-thumbnail"
                  style={divHeight} />
              </div>
            </div>
          </div>
        </Tab>
        <Tab
          label="User Information"
          data-route="/home">
          <div>
            <h2 className='tab_headline'>Tab Three</h2>
          </div>
        </Tab>
       </Tabs>
      )
     }
    }
class选项卡示例扩展组件{
建造师(道具){
超级(道具);
this.handleLoad=this.authorize.bind(this);
this.handleProfiles=this.handleProfiles.bind(this);
this.arr=[];
此.state={
信息:[],
详情:[]
}
}
componentDidMount(){
window.addEventListener('load',this.handleLoad);
}
handleAccounts=(响应)=>{
var详细信息=response.result.items;
console.log(响应)
这是我的国家({
信息:详情
});
details.map(x=>{
gapi.client.analytics.management.webproperties.list(
{'accountId':x.id})
.然后(这是手的财产)
.then(空,函数(错误){
控制台日志(err);
})
})
}
HandleProperty=(响应)=>{
//处理来自webproperties列表方法的响应。
if(response.result.items&&response.result.items.length){
//获取第一个Google Analytics帐户
var firstAccountId=response.result.items[0].accountId;
//获取第一个属性ID
var firstPropertyId=response.result.items[0].id;
//查询视图(配置文件)。
这个.queryProfiles(firstAccountId,firstPropertyId);
//console.log(firstPropertyId)
}否则{
log('未找到此用户的属性');
}
}
queryProfiles=(accountId,propertyId)=>{
//获取第一个属性的所有视图(纵断面)的列表
//第一个帐户。
gapi.client.analytics.management.profiles.list({
“accountId”:accountId,
“webPropertyId”:propertyId
})
.然后(这是手上的文件)
。然后(空,(错误)=>{
//记录所有错误。
控制台日志(err);
})
}
手控档案(回应){
//处理来自profiles列表方法的响应。
if(response.result.items&&response.result.items.length){
//获取第一个视图(纵断面)ID。
var firstProfileId=response.result.items[0].id;
//查询核心报告API。
//console.log(firstProfileId);
//this.querycoreportingapi(firstProfileId);
gapi.client.analytics.data.ga.get({
“ID”:“ga:”+firstProfileId,
‘开始日期’:‘30天Sago’,
“结束日期”:“今天”,
“指标”:“ga:会话,ga:反弹,ga:用户”
})
。然后((响应)=>{
//这是我的国家({
//详细信息:[this.state.details,response]
// })
此.arr.push(响应)
})
}否则{
log('找不到此用户的视图(配置文件)');
}
}
queryCoreReportingApi(档案ID){
console.log(profileID);
}
授权=(事件)=>{
var useimididate=event?false:true;
var authData={
客户id:客户id,
范围:范围,
immidate:使用immidate
};
gapi.auth.authorize(authData,(响应)=>{
gapi.client.load('analytics','v3')。然后(()=>{
//控制台日志(响应);
gapi.client.analytics.management.accounts.list()
。然后(这项计算);
});
});
}
render(){
返回(
{this.arr}
表二
表三
)
}
}
我正在将所有数据传递给以下组件:

import React, { Component } from 'react';
     class newsList extends Component {
     items = (props) => {
       if(props){
           return props.info.map((prop)=>{
               return(
                   <div>{prop.result.id}</div>
               )
           })
       }
     }

     render() {
        return(
            <div>
                <ul className="collection">
                    {console.log(this.state.details)}
                </ul>
            </div>
        )
     }
      }

     export default newsList;
import React,{Component}来自'React';
类newsList扩展组件{
物品=(道具)=>{
如果(道具){
返回道具信息地图((道具)=>{
返回(
{prop.result.id}
)
})
}
}
render(){
返回(
    {console.log(this.state.details)}
) } } 导出默认新闻列表;

当我看到控制台日志时,我可以看到
数组[]
。一开始它没有任何数据。过了一段时间,当我再次点击
Array[]
时,我可以看到它有两个对象。但是我不能用这些东西。如何才能做到这一点?

您当前的实施没有利用您的

目前,您的
arr
值仅附加到
,因此,React无法看到它何时更改

arr
值嵌入
React组件的
状态
将在每次使用更改时触发,从而使应用程序响应其值的更改

请参见下面的实施示例

初始化:

更新:

this.setState({
  arr: response
})
检索:

const arr = this.state.arr

您当前的实施没有利用您的

目前,您的
arr
值仅附加到
,因此,React无法看到它何时更改

arr
值嵌入
React组件的
状态
将在每次使用更改时触发,从而使应用程序响应其值的更改

请参见下面的实施示例

初始化:

更新:

this.setState({
  arr: response
})
检索:

const arr = this.state.arr

使用组件willreceiveprops怎么样??它在更新道具后处理渲染。感谢@agm1984的代码生成。我已经尝试了
componentWillMount()