React:使用 useEffect 从 API 获取数据

2025-06-04

React:使用 useEffect 从 API 获取数据

这篇文章将快速介绍如何利用 React 中的 useEffect 钩子从 API 中检索数据。

这篇文章假设您对如何从 API 获取/检索数据以及 React 和React Hooks的基础知识有一个大致的了解。

我们的组件

这里我们有一个简单的组件。

import React from 'react';
import './App.css';

function App() {
  return (
    <div className="App">
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

该组件将负责显示从我们获取的 API 中随机获取的一只狗的图像。为此,我们需要:

  1. 导入useStateuseEffect
  2. 通过 useState创建dogImage变量以及setDogImage函数
  3. 创建 useEffect 函数 — — 这是我们执行获取操作的地方
  4. 在我们的 useEffect 函数中,我们将使用setDogImage来将dogImage设置为我们收到的图像 URL
  5. 使用dogImage 作为图像的 src,以便我们可以显示随机

API

我们使用的 API几个不同的端点可供使用,但在这个简单示例中,我们只使用随机图像端点。此端点将返回一个包含消息键和状态键的对象,在这个简单示例中,我们只关注消息键。消息键将包含我们将用作图像源的 URL。

整合

// 1. Import *useState* and *useEffect*
import React, {useState, useEffect} from 'react';
import './App.css';

function App() {
    // 2. Create our *dogImage* variable as well as the *setDogImage* function via useState
    // We're setting the default value of dogImage to null, so that while we wait for the
    // fetch to complete, we dont attempt to render the image
  let [dogImage, setDogImage] = useState(null)

    // 3. Create out useEffect function
  useEffect(() => {
    fetch("https://dog.ceo/api/breeds/image/random")
    .then(response => response.json())
        // 4. Setting *dogImage* to the image url that we received from the response above
    .then(data => setDogImage(data.message))
  },[])

  return (
    <div className="App">
        {/* 5. Using *dogImage as* the *src* for our image*/}
    {dogImage && <img src={dogImage}></img>}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

如果我们的消息返回一个 URL 数组,如下所示:

// API Used: https://dog.ceo/api/breeds/image/random/3
// Returns:
{
    "message": [
        "https://images.dog.ceo/breeds/setter-irish/n02100877_1453.jpg",
        "https://images.dog.ceo/breeds/buhund-norwegian/hakon3.jpg",
        "https://images.dog.ceo/breeds/dane-great/n02109047_31049.jpg"
    ],
    "status": "success"
}
Enter fullscreen mode Exit fullscreen mode

我们可以做以下事情:

// 1. Import *useState* and *useEffect*
import React, {useState, useEffect} from 'react';
import './App.css';

function App() {
    // 2. Create our *dogImage* variable as well as the *setDogImage* function via useState
    // We're setting the default value of dogImage to null, so that while we wait for the
    // fetch to complete, we dont attempt to render the image
  let [dogImage, setDogImage] = useState(null)

    // 3. Create out useEffect function
  useEffect(() => {
    fetch("https://dog.ceo/api/breeds/image/random/3")
    .then(response => response.json())
        // 4. Setting *dogImage* to the image url that we received from the response above
    .then(data => setDogImage(data.message))
  },[])

  return (
    <div className="App">
        {/* 5. Returning an img element for each url, again with the value of our src set to the image url */}
    {dogImage && dogImage.map((dog) => <img width={"200px"} height={"200px"} src={dog}></img>)}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

就是这样!您可以查看此 Replit 上的实时演示并自行探索代码。

与往常一样,请参阅文档以获取更多信息:
MDN — Fetch

React Hooks

狗 API

如有任何问题、建议或打招呼,请随时在这里或通过我的社交媒体联系我👋

文章来源:https://dev.to/antdp425/react-fetch-data-from-api-with-useeffect-27le
PREV
JavaScript 正在吞噬世界
NEXT
CSS 网格简化!AWS GenAI 上线!