简体   繁体   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

Here is the code which I have written to get the details of the match from the API.这是我编写的代码,用于从 API 获取匹配的详细信息。 I am getting the data and converting it into JSON format.我正在获取数据并将其转换为 JSON 格式。 I am able to add data to the match array, but I can't render it to screen.我可以将数据添加到匹配数组,但无法将其呈现到屏幕上。

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>
    );
  }
}

Here is the data I am getting.这是我得到的数据。 I am getting the match unique id and through which I am getting the the details of th match such as stats, scorecard, summary etc. It is printing in the console but not rendering on the page.我正在获取匹配唯一 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 更新状态。

The render function should be a pure function returning a result to display, there should be no side-effects such as fetching data.渲染函数应该是一个纯函数,返回结果显示,不应该有获取数据等副作用。 Instead, use one of the react component lifecycle functions (or callback) to issue side-effects and/or update state.相反,使用 react 组件生命周期函数(或回调)之一来发出副作用和/或更新状态。 You also are directly mutating state.你也直接改变状态。

First compute an entire object you wish to set state to/with and call setState with the new state object.首先计算您希望将状态设置为/使用的整个对象,然后使用新的状态对象调用setState In this case, you can queue up all your fetch requests and process them "in bulk" using Promise.all .在这种情况下,您可以使用Promise.all将所有获取请求排队并“批量”处理它们。 I also suggest surrounding all your async processing with a try/catch in case errors happen so you can handle it and keep your app on the happy path.我还建议使用 try/catch 来处理所有异步处理,以防发生错误,以便您可以处理它并使您的应用程序保持在愉快的路径上。

Also, ensure you are setting the button's onClick callback correctly.另外,请确保正确设置按钮的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.

相关问题 我无法从此 API 获取数据。 这是代码 - I am unable to fetch data from this API. Here is the code 我想从 api 获取数据(姓名和电子邮件)。 我的程序已成功编译,但我在控制台中遇到错误。 https://randomuser.me/api - I am suppose to fetch data (name & email) from api. My program is compiled sucessfully but I'm getting errors in console. https://randomuser.me/api 我可以只渲染我的页面一次。 刷新页面后,我收到一个错误,因为无法从 api 中找到数据。请让我知道我的错误 - I can render my page just once. After refreshing the page, i am getting an error as cant find data from api. Please let me know my mistake 我无法使用 map api 数据数组 我在过去两天尝试了几种方法 - i am not able to map the api data array i have tried several methods from last two days My Javascript JSON code in HTML page does not render the RESTful API array objects, although I get the data from the API. 我应该怎么办? - My Javascript JSON code in HTML page does not render the RESTful API array objects, although I get the data from the API. What should I do? 如何将我从 API 获取的数据插入到离子卡中? - How to insert the data that I am getting from a API in to ionic cards? NextJS:我从 api json 数据中得到未定义 - NextJS: I am getting undefined from api json data 我正在尝试使用天气api,我正在尝试从中获取数据但未定义但属性确实存在 - I am trying to use a weather api that I am trying to pull data from i am getting undefined but the property does exist 当我加载 api 请求并且我的反应组件尝试呈现时,我总是收到数据未定义错误 - I am always getting a data is undefined error when I am loading a api request and my react component trys to render 尝试通过crunchbase API提取JSON数据。 我究竟做错了什么? - Trying to pull JSON data via the crunchbase API. What am I doing wrong?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM