首頁 > web前端 > js教程 > 主體

如何在 ReactJS 中使用 Axios - GET 和 POST 請求

Susan Sarandon
發布: 2024-10-15 12:24:01
原創
994 人瀏覽過

Cara Penggunaan Axios di ReactJS - GET dan POST Request

如何在 ReactJS 中使用 Axios

介紹

Axios 是一個流行的函式庫,用於執行 GET、POST、PUT、DELETE 等 HTTP 請求。 Axios 非常適合在 React 應用程式中使用,因為它提供簡單的語法並支援 Promises。本文將討論如何在 ReactJS 應用程式中使用 Axios。

Axios 安裝
確保你的 React 專案中安裝了 Axios:

npm install axios
登入後複製

在 React 元件中使用 Axios
例如,我們希望使用 GET 方法從 API 檢索資料並將其顯示在 React 元件中。

  1. 取得請求:
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const App = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        setData(response.data);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;

登入後複製

說明:

  • 在元件首次載入時使用useEffect呼叫fetchData函數。
    • axios.get 用於從 API URL 檢索資料。
    • 狀態資料、載入和錯誤用於儲存檢索到的資料、載入狀態和錯誤。

  1. POST 請求: 若要傳送數據,可以使用POST方法,如下所示:
import React, { useState } from 'react';
import axios from 'axios';

const App = () => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
        title,
        body,
      });
      console.log('Response:', response.data);
      alert('Post successfully created!');
    } catch (error) {
      console.error('Error posting data:', error);
    }
  };

  return (
    <div>
      <h1>Create a Post</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <textarea
          placeholder="Body"
          value={body}
          onChange={(e) => setBody(e.target.value)}
        ></textarea>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default App;

登入後複製

說明

  • axios.post 方法用於將標題和正文資料傳送到 API。
  • handleSubmit 函數處理表單提交並將資料傳送到伺服器。

以上是如何在 ReactJS 中使用 Axios - GET 和 POST 請求的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!