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

领域

我的项目目的是从 Google Analytics 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>
      )
     }
    }

我将所有数据传递给以下组件:

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;

当我看到控制台日志时,我可以看到Array [ ]. 一开始它没有任何数据。一段时间后,当我再次单击时,Array [ ]我可以看到它有 2 个对象。但我不能使用这些对象。我怎样才能做到这一点?

阿曼查兰

您当前的实现没有使用您React Componentstate.

目前,您的arr值只是附加到this,因此,React 无法看到它何时发生变化。

将您的arr嵌入您React component'sstate将在render()每次使用 更改时触发this.setState(),从而使您的应用程序能够响应其值的变化。

请参阅下面的实施示例。

在里面:

constructor(props) {
   super(props)
   this.state: {
     arr: []
   }
 }

更新:

this.setState({
  arr: response
})

取回:

const arr = this.state.arr

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章