如何解决axios承诺



我正在从neneneba API开发GET请求,我得到的响应是图像中的响应,我在承诺中看到的数据是正确的。我想做的是在HTML结构中呈现字母及其promise数据,但作为异步请求,它会作为promise返回,我需要在HTML结构中返回promise数据

[https://prnt.sc/11e8fmb][1]

import React from 'react';
import {Card} from 'react-bootstrap';
import axios from 'axios';
const Home = (index) =>{
const renderCard = (card) => {
return(
<React.Fragment>
<Card style={{width: "18rem"}}>
<Card.Img width="100" height="250" variant="top" src="holder.js/100px180" src={card.image}/>
</Card>
<Card.Body>
<Card.Title>{card.title}</Card.Title>
<Card.Text>{card.text}</Card.Text>
</Card.Body>
</React.Fragment>            
);
}
const response = axios.get('http://localhost:8000/api/Equipos/?format=json')
.then((response) => {
const cartas = [];
for (let index = 0; index < 20; index++) {     
const respuesta = response.data[index];
var titulo = respuesta.Equipo;
var valor = respuesta.ValorMedio;
const cardInfo =                 
{
image: "https://cdn5.dibujos.net/dibujos/pintados/201746/escudo-del-club-atletico-de-madrid-deportes-escudos-de-futbol-11197949.jpg",
title:titulo,
text: valor
}
cartas.push(renderCard(cardInfo));
}
return cartas;
}); 
const cartas = Promise.resolve(response);        
console.log(cartas);
return(
<div class="row mt-5 ml-5">
<div class="col-3">
//Here i want to render the card data
</div>
<div class="col-3">
//Here i want to render the card data
</div>
<div class="col-3">
//Here i want to render the card data
</div>
<div class="col-3">
//Here i want to render the card data
</div>
</div>
);
}
export default Home;

[1]: https://prnt.sc/11e8fmb

要渲染卡,您必须在每个请求上使用asyncawait来处理异步请求,要使用react渲染卡,必须考虑生命周期。一旦您有了数据,render函数就会自动渲染数据并返回HTML结构。

import React from 'react';
import axios from 'axios';
// Estructura de los datos en React
export default class FetchEquipo extends React.Component {
state = {
loading: true,
equipo: null,
jugadores: null,
edadMedia: null,
valorTotal: null,
valorMedio: null
};
// Inicio de la petición asincrona a la API
async componentDidMount() {
const url = "http://localhost:8000/api/Equipos/?format=json";
// Await de la función para esperar a la respuesta asincrona y obtener los datos
const response = await axios.get(url);
const data = await response.data;
// Cambio del estado de los datos porque llegado aquí ya se han recibido
for (let index = 0; index < data.length; index++) {
this.setState({ equipo: data[index], loading: false });
}
}
render() {
if (this.state.loading == true) {
return (
<div>
<p>Loading...</p>
</div>
);
}
else if (this.state.equipo == null) {
return (
<div>
<p>No se encontraron datos de los equipos</p>
</div>
);
}
else{
return (
<div>
<h1>{this.state.equipo.Equipo}</h1>
<h2>Jugadores: {this.state.equipo.Jugadores}</h2>
<h2>Edad media: {this.state.equipo.EdadMedia}</h2>
<h2>Valor total: {this.state.equipo.ValorTotal}</h2>
<h2>Valor Medio: {this.state.equipo.ValorMedio}</h2>
</div>
);
}
}
}

最新更新