【问题标题】:Map JSON from API Javascript从 API Javascript 映射 JSON
【发布时间】:2022-01-10 17:26:58
【问题描述】:

我正在使用 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;

【问题讨论】:

    标签: javascript reactjs api axios


    【解决方案1】:

    首先,第一个 api 响应是一个带有 inforesults 的对象,因此您可能希望将结果分配给您的状态:

    this.setState({
          p1: firstResponse.data.results,
          p2: secondResponse.data
    });
    

    接下来,在第一次挂载时,该状态将为空,因此您可以使用条件链接防止其渲染更改此行:

    {this.state.p1?.map((persona, id) => {
    

    【讨论】:

    • 或者您可以将初始 state.p1 设置为空数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 2019-01-31
    • 2022-10-05
    相关资源
    最近更新 更多