Here is the code which I have written to get the details of the match from the API. I am getting the data and converting it into JSON format. 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.
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. 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. In this case, you can queue up all your fetch requests and process them "in bulk" using 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.
Also, ensure you are setting the button's onClick
callback correctly.
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>
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.