繁体   English   中英

我正在从 API 请求数据。 目前,我以对象数组的形式获取数据,但无法在浏览器上呈现输出

[英]I am requesting data from an API. Currently, I am getting data as an array of objects but I'm not able to render output on the browser

这是我编写的代码,用于从 API 获取匹配的详细信息。 我正在获取数据并将其转换为 JSON 格式。 我可以将数据添加到匹配数组,但无法将其呈现到屏幕上。

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    match: [
      { id: '12', stat: 'he', score: 's',description:'sds'},
      { id: '', stat: '', score: '',description:''},
      { id: '', stat: '', score: '',description:''},
      { id: '', stat: '', score: '',description:''},
      { id: '', stat: '', score: '',description:''}

    ],
    otherState: 'some other value'
  }

  GetMatchNumber = async () => {
    const responseofmatchno = await fetch(`https://cricapi.com/api/matches?apikey={API_KEY}`);
    const dataofmatchno = await responseofmatchno.json(); 
    const length = dataofmatchno.matches.length;
    var actual_length=0;
    var p=0;
    let true_value = "true";
    while(++p < length)
    {
      if((dataofmatchno.matches[p].matchStarted.valueOf()) === (dataofmatchno.matches[0].matchStarted))
      {
        actual_length = actual_length + 1;
      }
    }
    let i = 0;
    let j=0;
    while(++i < 4)
    {
      j=dataofmatchno.matches[i].unique_id;
      this.state.match[i].id=(dataofmatchno.matches[i].unique_id);
      console.log(this.state.match[i].id);
      const responseofmatchdetails = await fetch(`http://cricapi.com/api/cricketScore?unique_id=${j}&apikey={API_KEY}`);
      const dataofmatch = await responseofmatchdetails.json();
      this.state.match[i].stat=(dataofmatch.stat);
      console.log(this.state.match[i].stat);
      this.state.match[i].score=(dataofmatch.score);
      console.log(this.state.match[i].score);
      this.state.match[i].description=(dataofmatch.description);
      console.log(this.state.match[i].description);
    }
  }
  render () {
    console.log(this.state.match[0].id);
    return (
      <div className="App">
        <h1>Hi, I'm a React App</h1>
        <p>This is really working!</p>
        <p>{this.state.match[0].id}</p>
        <button onClick= {this.GetMatchNumber()}></button>
        <Person 
          id={this.state.match[0].id} 
          stat={this.state.match[0].stat} />
        <Person 
          id={this.state.match[1].id} 
          stat={this.state.match[1].stat} />
        <Person 
          id={this.state.match[2].id} 
          stat={this.state.match[2].stat} />
      </div>
    );
  }
}

这是我得到的数据。 我正在获取匹配唯一 ID,并通过它获取匹配的详细信息,例如统计信息、记分卡、摘要等。它在控制台中打印,但不在页面上呈现。

1197802
App.js:51 Otago Women won by 31 runs
App.js:53 Canterbury Women 91/10 * v Otago Women 122/7 
App.js:55 Canterbury Women 91/10 * v Otago Women 122/7 
App.js:46 1187027
App.js:51 Australia won by 10 wickets (with 74 balls remaining)
App.js:53 India 255/10  v Australia 258 *
App.js:55 India 255/10  v Australia 258 *
App.js:46 1195608
App.js:51 Heat won by 7 wickets (with 28 balls remaining)
App.js:53 Brisbane Heat 114/3 * v Adelaide Strikers 110/10 
App.js:55 Brisbane Heat 114/3 * v Adelaide Strikers 110/10 

尝试在 componentDidMount 中调用 API,因为它将被调用一次(仅第一次渲染)然后使用 this.setState 更新状态。

渲染函数应该是一个纯函数,返回结果显示,不应该有获取数据等副作用。 相反,使用 react 组件生命周期函数(或回调)之一来发出副作用和/或更新状态。 你也直接改变状态。

首先计算您希望将状态设置为/使用的整个对象,然后使用新的状态对象调用setState 在这种情况下,您可以使用Promise.all将所有获取请求排队并“批量”处理它们。 我还建议使用 try/catch 来处理所有异步处理,以防发生错误,以便您可以处理它并使您的应用程序保持在愉快的路径上。

另外,请确保正确设置按钮的onClick回调。

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    match: [
      { id: '12', stat: 'he', score: 's',description:'sds'},
      { id: '', stat: '', score: '',description:''},
      { id: '', stat: '', score: '',description:''},
      { id: '', stat: '', score: '',description:''},
      { id: '', stat: '', score: '',description:''}

    ],
    otherState: 'some other value'
  }

  getMatchNumber = async () => {
    const responseOfmatchNo = await fetch(`https://cricapi.com/api/matches?apikey={API_KEY}`);
    const dataOfMatchNo = await responseOfmatchNo.json();

    const resolvedFetchedJSON = await Promise.all(
      // map data objects to fetch requests, returns json data
      dataOfMatchNo.matches.map(request => {
        return fetch(`http://cricapi.com/api/cricketScore?unique_id=${request.unique_id}&apikey={API_KEY}`)
        .then(response => response.json());
      })
    );

    // at this point I think you have the array of JSON data you were copying previously
    this.setState({ match: resolvedFetchedJSON });

    /**
     * NOTE: if you want to keep existing matches in state, i.e. merge in new data then
     * this.setState(prevState => ({ match: [...prevState.match, ...resolvedFetchedJSON]}));
     */
  }

  render () {
    console.log(this.state.match[0].id);
    return (
      <div className="App">
        <h1>Hi, I'm a React App</h1>
        <p>This is really working!</p>
        <p>{this.state.match[0].id}</p>
        {/* <button onClick= {this.GetMatchNumber()}></button> */}
        {
          /**
           * Don't invoke onClick callback immediately, either
           *  - define in-line callback
           *    <button onClick= {() => this.GetMatchNumber()}></button>
           *  - or set callback as your function, notice no parans on function 
           *    <button onClick= {this.GetMatchNumber}></button>
           */
        }
        <button onClick= {this.GetMatchNumber}></button>
        <Person 
          id={this.state.match[0].id} 
          stat={this.state.match[0].stat} />
        <Person 
          id={this.state.match[1].id} 
          stat={this.state.match[1].stat} />
        <Person 
          id={this.state.match[2].id} 
          stat={this.state.match[2].stat} />
      </div>
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM