[英]Map JSON from API Javascript
I am making two calls from API with Axios, it works and it brings me the two results I need, the problem is that I want to iterate through my first Axios call, but It says:我从 API 和 Axios 打了两个电话,它有效,它给我带来了我需要的两个结果,问题是我想遍历我的第一个 Axios 调用,但它说:
./src/app.js
Line 29:34: 'p1' is not defined no-undef
Search for the keywords to learn more about each error
I have been looking on Google how to map a JSON, but none of them have a similar situation.我一直在谷歌上寻找如何 map 和 JSON,但没有一个有类似的情况。 How could I map my first API call results?我怎么能 map 我的第一个 API 呼叫结果?
Thank you in advance.先感谢您。
Here is my code.这是我的代码。
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;
First of all, the first api response is an object with info
and results
, so you may want to assign results to your state:首先,第一个 api 响应是带有info
和results
的 object ,因此您可能希望将结果分配给您的 state:
this.setState({
p1: firstResponse.data.results,
p2: secondResponse.data
});
Next, on the first mount that state will be null, so you can prevent its render changing this line using conditional chaining:接下来,在第一次安装时 state 将是 null,因此您可以使用条件链接防止其渲染更改此行:
{this.state.p1?.map((persona, id) => {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.