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 (
);
} 删除产品.tsx
import { BASE_URL } from '../App';
export default function DeleteProduct({ id }: { id: number }) {
const handleDelete = async () => {
try {
const response = await fetch(`${BASE_URL}/${id}`, {
method: 'DELETE',
});
const result = await response.json();
console.log('Product Deleted Succesfully', result);
alert('Product has been delete');
} catch (error) {
console.log('Failed Delete Product', error);
alert('Failed Delete Product');
}
};
return ;
}编辑产品.tsx
import { useState } from 'react';
import { BASE_URL } from '../App';
export default function EditProduct({
id,
prevTitle,
prevPrice,
prevDescription,
prevImage,
prevCategory,
}: {
id: number;
prevTitle: string;
prevPrice: number;
prevDescription: string;
prevImage: string;
prevCategory: string;
}) {
const [title, setTitle] = useState(prevTitle);
const [price, setPrice] = useState(prevPrice);
const [description, setDescription] = useState(prevDescription);
const [image, setImage] = useState(prevImage);
const [category, setCategory] = useState(prevCategory);
const [open, setOpen] = useState(false);
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}/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title,
price,
description,
image,
category,
}),
});
const result = await response.json();
console.log('Product edited:', result);
alert('Product edited successfully!');
} catch (error) {
console.log('Error editing product', error);
alert('Failed edit product');
}
};
return (
<>
>
);
} 结论
感谢您花时间阅读这篇文章。我希望这些代码示例能为如何在没有外部库的情况下处理 React.js 中的 API 提供一些有用的见解。如果您有兴趣探索完整的项目,请随时访问代码存储库:https://github.com/rfkyalf/reactjs-api-handling。
如果您有任何建议或问题,请随时在评论部分分享。我随时欢迎反馈和讨论!
我总是很高兴在网络开发项目上与他人联系和合作。您可以通过访问我的作品集网站来了解有关我的作品和过去项目的更多信息:https://www.rifkyalfarez.my.id。