我正在使用 Axios 從 API 進行兩次呼叫,它可以作業并為我帶來了我需要的兩個結果,問題是我想遍歷我的第一個 Axios 呼叫,但它說:
./src/app.js
Line 29:34: 'p1' is not defined no-undef
Search for the keywords to learn more about each error
我一直在谷歌上尋找如何映射 JSON,但沒有一個有類似的情況。如何映射我的第一個 API 呼叫結果?
先感謝您。
這是我的代碼。
import React, { Component } from "react";
import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";
const urlPersonas = "https://randomuser.me/api/?results=20&inc=id,name,picture";
const urlMascotas = "https://dog.ceo/api/breeds/image/random/20";
class App extends Component {
state = {
p1: null,
p2: null,
};
async componentDidMount() {
const [firstResponse, secondResponse] = await Promise.all([
axios.get(urlPersonas),
axios.get(urlMascotas),
]);
this.setState({
p1: firstResponse.data,
p2: secondResponse.data,
});
}
render() {
//Check if the data from my first API call exists
console.log(this.state.p1);
return (
<div className="App">
<br />
<button className="btn btn-success text-center">Agregar persona</button>
<br /> <br />
<table className="table">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Foto</th>
<th>Mascota</th>
<th>Foto</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
//Here is the problem
{this.state.p1.data.map((persona, id) => {
return (
<tr>
<td>{id}</td>
<td>{persona.name.first}</td>
<td>{persona.name.last}</td>
<td>{persona.picture.medium}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}
export default App;
uj5u.com熱心網友回復:
首先,第一個 api 回應是一個帶有infoand的物件results,因此您可能希望將結果分配給您的狀態:
this.setState({
p1: firstResponse.data.results,
p2: secondResponse.data
});
接下來,在第一次掛載時,該狀態將為空,因此您可以使用條件鏈接防止其渲染更改此行:
{this.state.p1?.map((persona, id) => {
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373518.html
標籤:javascript 反应 接口 公理
下一篇:如何在URI中轉義花括號
