开发者问题收集

在 ReactJS (函数组件) 中通过 API 映射和渲染数据

2021-11-15
860

我正在学习 React。需要从 ReactJS(函数组件)中的 tinyfac.es API 映射 5 张图片。图片正在正确获取(在控制台中),但无法呈现。如果可能,请解释错误。

代码:

import axios from "axios";
import React from "react";
import { useState, useEffect } from "react";

let base_url = `https://tinyfac.es/api/data?limit=50&quality=0`;

function Storyslider() {
  const [Containers, setContainers] = useState([]);
  useEffect(() => {
    axios
      .get(base_url)
      .then((a) => {
        console.log(a.data[0].url);
        setContainers(a.data.results);
      })
      .catch((b) => {
        console.log(Error);
      });
  }, []);
  return (
    <div>
      {Containers &&
        Containers.map((Contain, index) => (
          <img
            src={Contain.data[0].url}
            alt={Contain.data[0].gender}
            key={index}
          />
        ))}
    </div>
  );
}

export default Storyslider;
2个回答

data 对象内没有 results 键。因此,您的数据未正确设置到 Containers 状态。

这是您的工作代码:

import axios from "axios";
import React from "react";
import { useState, useEffect } from "react";

let base_url = `https://tinyfac.es/api/data?limit=50&quality=0`;

function Storyslider() {
  const [Containers, setContainers] = useState([]);
  useEffect(() => {
    axios
      .get(base_url)
      .then((a) => {
        console.log(a.data);
        setContainers(a.data);
      })
      .catch((b) => {
        console.log(Error);
      });
  }, []);
  return (
    <div>
      {Containers &&
        Containers.map((Contain, index) => (
          <img
            src={Contain?.url}
            alt={Contain?.gender}
            key={index}
          />
        ))}
    </div>
  );
}

export default Storyslider

如果您想从数组中渲染单个图像(或第一张图像),您只需执行

{Containers && <img src={Containers[0].url} alt={Containers[0].gender} />}
Pradip Dhakal
2021-11-15

调用 setContainers(a.data.results) 将导致 container 状态为 undefined ,因为您返回的数据上没有 results 键。以下是您尝试的一个简化工作示例:

import axios from "axios";
import { useState, useEffect } from "react";

let base_url = `https://tinyfac.es/api/data?limit=50&quality=0`;

function Storyslider() {
  const [containers, setContainers] = useState([]);
  useEffect(() => {
    axios
      .get(base_url)
      .then((a) => {
        setContainers(a.data);
      })
      .catch((b) => {
        console.log(Error);
      });
  }, []);
  return (
    <div>
      {containers.map((contain, index) => (
        <img src={contain.url} alt={contain.gender} key={index} />
      ))}
    </div>
  );
}

export default Storyslider;

Edit angry-fast-upe615

Youssouf Oumar
2021-11-15