React.js API 处理

在本文中,我想分享我在不使用任何外部库的情况下在 React.js 中处理 API 请求的经验。它包括使用 HTTP 方法(如 GET、POST、PATCH 和 DELETE)同时实现搜索、分页、排序和过滤等功能。这种方法帮助我更好地理解了 React.js 和 API 处理的核心概念。我希望我的见解对任何探索类似实现的人都有用。

我不会给出任何解释——只给出代码本身。所以,让代码自己说话吧!

应用程序.tsx

import { useEffect, useState } from 'react';
import AddProduct from './components/AddProduct';
import DeleteProduct from './components/DeleteProduct';
import EditProduct from './components/EditProduct';

interface Product {
  id: number;
  title: string;
  description: string;
  category: string;
  price: number;
  image: string;
}

export const BASE_URL = 'https://fakestoreapi.com/products';

export default function App() {
  const [products, setProducts] = useState([]);
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState('');
  const [sortBy, setSortBy] = useState('');
  const [orderBy, setOrderBy] = useState('');
  const [limit, setLimit] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);

  const totalPages = Math.ceil(products.length / limit);

  const handleSearch = (e: React.ChangeEvent) => {
    const term = e.target.value;
    if (!term.startsWith(' ')) setQuery(term);
  };

  const handlePrev = () => {
    if (currentPage > 1) setCurrentPage(currentPage - 1);
  };

  const handleNext = () => {
    if (currentPage < totalPages) setCurrentPage(currentPage + 1);
  };

  useEffect(() => {
    const fetchProducts = async () => {
      const response = await fetch(BASE_URL);
      const result = (await response.json()) as Product[];
      const filteredProducts = result
        .filter((product) =>
          product.title.toLocaleLowerCase().includes(query.toLocaleLowerCase())
        )
        .filter((product) => (category ? product.category === category : true))
        .sort((a, b) => {
          if (sortBy === 'title') {
            return orderBy === 'des'
              ? b.title.localeCompare(a.title)
              : a.title.localeCompare(b.title);
          }
          if (sortBy === 'price') {
            return orderBy === 'des' ? b.price - a.price : a.price - b.price;
          }
          return orderBy === 'des' ? b.id - a.id : a.id - b.id;
        });

      setProducts(filteredProducts);
      setCurrentPage(1);
    };

    fetchProducts();
  }, [category, query, sortBy, orderBy]);

  const paginatedProducts = products.slice(
    (currentPage - 1) * limit,
    currentPage * limit
  );

  return (
    
page {currentPage} of {totalPages || 1}
{paginatedProducts.map((product) => (

{product.title}

{product.category}

${product.price}

 | 
))}
); }

添加产品.tsx

import { useState } from 'react';
import { BASE_URL } from '../App';

export default function AddProduct() {
  const [title, setTitle] = useState('');
  const [price, setPrice] = useState('');
  const [description, setDescription] = useState('');
  const [image, setImage] = useState('');
  const [category, setCategory] = useState('jewelery');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!title || !price || !description || !image || !category) {
      alert('Please fill out all fields');
      return;
    }

    try {
      const response = await fetch(`${BASE_URL}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          title,
          price,
          description,
          image,
          category,
        }),
      });

      const result = await response.json();
      console.log('Product created:', result);

      setTitle('');
      setPrice('');
      setDescription('');
      setImage('');
      setCategory('jewelery');
      alert('Product added successfully!');
    } catch (error) {
      console.log('Error creating product', error);
      alert('Failed create product');
    }
  };

  return (
    
setTitle(e.target.value)} /> setPrice(Number(e.target.value))} />