You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中如何基于URL调用API?重渲染后调用实现指南

Hey there! Since you're new to React, let's walk through how to call that News API using both fetch and axios, and make sure the call behaves correctly when your component re-renders. The key here is using React's useEffect hook to control when the API request runs—this prevents unnecessary duplicate calls on every re-render.

Using fetch (built into browsers, no extra install needed)

First, we'll use React's useState to store the fetched news data, loading state, and any errors. Then useEffect will trigger the API call at the right time.

import { useState, useEffect } from 'react';

function NewsComponent() {
  const [newsData, setNewsData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  // API URL (you can extract params into variables for easier updates later)
  const apiUrl = 'http://newsapi.org/v2/everything?q=tech&apiKey=008c2c412a2b403698bc29a732374513&pageSize=10&page=1';

  useEffect(() => {
    // Async function to handle the API call
    const fetchNews = async () => {
      setIsLoading(true);
      try {
        const response = await fetch(apiUrl);
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        setNewsData(data);
        setError(null);
      } catch (err) {
        setError(err.message);
        setNewsData(null);
      } finally {
        setIsLoading(false);
      }
    };

    fetchNews();

    // Empty dependency array = runs ONLY on first component mount
    // If you need to re-run when a value changes (like page number), add it here: [page]
  }, []);

  // Render based on current state
  if (isLoading) return <div>Loading news...</div>;
  if (error) return <div>Oops! Error: {error}</div>;

  return (
    <div>
      <h2>Latest Tech News</h2>
      {newsData?.articles?.map((article, index) => (
        <div key={index} style={{ marginBottom: '1rem' }}>
          <h3>{article.title}</h3>
          <p>{article.description}</p>
        </div>
      ))}
    </div>
  );
}

export default NewsComponent;

Key Re-render Note:

The empty [] dependency array in useEffect ensures the API call runs only once when the component mounts, not on every re-render. If you later add pagination (changing the page parameter), add page to the dependency array ([page])—this will trigger a new API call whenever the page value updates.

Using axios (third-party library, cleaner request syntax)

First, install axios via npm or yarn:

npm install axios
# or
yarn add axios

Then use it in your component with similar state and effect logic:

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

function NewsComponent() {
  const [newsData, setNewsData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  const apiUrl = 'http://newsapi.org/v2/everything?q=tech&apiKey=008c2c412a2b403698bc29a732374513&pageSize=10&page=1';

  useEffect(() => {
    const fetchNews = async () => {
      setIsLoading(true);
      try {
        const response = await axios.get(apiUrl);
        setNewsData(response.data);
        setError(null);
      } catch (err) {
        setError(err.response?.data?.message || err.message);
        setNewsData(null);
      } finally {
        setIsLoading(false);
      }
    };

    fetchNews();

    // Control re-runs with the dependency array here
  }, []);

  // Render logic matches the fetch example
  if (isLoading) return <div>Loading news...</div>;
  if (error) return <div>Oops! Error: {error}</div>;

  return (
    <div>
      <h2>Latest Tech News</h2>
      {newsData?.articles?.map((article, index) => (
        <div key={index} style={{ marginBottom: '1rem' }}>
          <h3>{article.title}</h3>
          <p>{article.description}</p>
        </div>
      ))}
    </div>
  );
}

export default NewsComponent;

Why Choose Axios?

  • It automatically parses JSON responses (no need for await response.json()).
  • It handles error responses more intuitively—you can access err.response to get detailed failure info.

内容的提问来源于stack exchange,提问作者T dhanunjay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:07:31